如何使用Knockout JS应用绑定并保持输入值? [英] How to applyBindings and keep input values with Knockout JS?

查看:97
本文介绍了如何使用Knockout JS应用绑定并保持输入值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个HTML/KnockoutJS应用程序.我的网络服务器返回一个表单,其中包含带有信息的输入字段.当我更新模型并执行ko.applyBindings时,输入值自然会被模型覆盖.

I'm building a HTML/KnockoutJS application. My webserver returns a form with input fields with information. When I new up my model and do an ko.applyBindings, naturally the input values are overwritten by the model.

是否有一种方法可以自动在ko.applyBindings中自动将输入字段的数据加载到模型中?

Is there a way to do an ko.applyBindings in which the model is automatically loaded with the data of the input fields?

示例: https://jsfiddle.net/KeesCBakker/p7ygq5y2/1/

HTML:

Title: <input data-bind="textInput: title" value="MyTitle" placeholder="Nothing here!" /><br/>
Text: <input data-bind="textInput: text" value="MyText" placeholder="Nothing here!" /><br/>
<button id="bind">Bind!</button>

JS:

ko.bindingHandlers.initFromInput = {
  init: function(element, valueAccessor) {
    valueAccessor()(element.value);
  }
};

function Model() {
  this.title = ko.observable();
  this.text = ko.observable();
}

document.getElementById('bind').onclick = function() {

  var model = new Model();
  ko.applyBindings(model);

};

推荐答案

您可以使用自定义绑定,告诉Knockout将输入值用作默认值,如下所示:

You could use a custom binding, that tells Knockout to use the input values as default, like this:

ko.bindingHandlers.initFromInput = {
    init: function(element, valueAccessor) {
        valueAccessor()(element.value);
    }
};

这是一个jsfiddle: http://jsfiddle.net/kv3zras3/3/

Here's a jsfiddle: http://jsfiddle.net/kv3zras3/3/

有了新的绑定,您的数据绑定应该看起来像这样:

With the new binding, your data-binds should look something like this:

<input data-bind="initFromInput: title, value: title" value="MyTitle" placeholder="Nothing here!" />
<input data-bind="initFromInput: text, value:text" value="MyText" placeholder="Nothing here!" />

如果使绑定看起来像这样,还有一种更好的方法可以实现此目的:

There's an abit nicer way of achieving this, if you make like binding look like this:

var origValueInput = ko.bindingHandlers.value.init;
ko.bindingHandlers.value.init = function(element, valueAccessor, allBindings) {
    if (allBindings.has('initValueFromInput')) {
        valueAccessor()(element.value);
    }
    origValueInput.apply(this, arguments);
};

您可以这样编写数据绑定:

You can write your data-binds like this:

<input value="MyTitle" data-bind="initValueFromInput, value: title"/>
<input value="MyText" data-bind="initValueFromInput, value: text"/>

这是一个小提琴: https://jsfiddle.net/yy51kok5/

这篇关于如何使用Knockout JS应用绑定并保持输入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆