[英]Knockout JS - data-bind multiple values
Question about JS Knockout library - I have three inputs, all data-Bind-ed to the same variable. 关于JS Knockout库的问题 - 我有三个输入,所有数据都绑定到同一个变量。 Two have a boolean value of false and one has a boolean value of true. 两个的布尔值为false,一个布尔值为true。 (I can't change them to ints, unfortunately, which would make this problem easier). (不幸的是,我无法将它们改为整体,这会使这个问题变得更容易)。 Although the two false-valued inputs share behavior, I need to differentiate between them somehow to trigger slightly different behaviors. 虽然这两个虚假输入共享行为,但我需要以某种方式区分它们以触发稍微不同的行为。
Is it possible to data-bind each to another variable, with different values? 是否可以将每个数据绑定到另一个具有不同值的变量? So instead of each being 而不是每个人
<input data-Bind="checked:test" value="false">
I would have something like 我会有类似的东西
<input data-Bind="test, test2" value="false, 1">
and 和
<input data-Bind="test, test2" value="false, 2">?
I tried that directly and didn't work so I don't know if it's possible. 我直接尝试了,但没有用,所以我不知道是否可能。 Thanks so much. 非常感谢。
You cant bind multiple variables directly but creating a custom bind function do the trick for you. 您无法直接绑定多个变量,但创建自定义绑定函数可以帮到您。
Example : http://jsfiddle.net/gurkavcu/ePW8Y/ 示例: http : //jsfiddle.net/gurkavcu/ePW8Y/
** Change input value (true , false) to trigger the update function **更改输入值(true,false)以触发更新功能
HTML HTML
<input data-bind="customData: test , v1 : test2"/>
<div>
<span data-bind ="text : test"/>
</div>
<div>
<span data-bind ="text : test2"/>
</div>
JS JS
ko.bindingHandlers.customData = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).change(function () {
valueAccessor()(element.value);
});
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var value =ko.utils.unwrapObservable(valueAccessor());
var v1 = allBindingsAccessor().v1;
if(value === "true") {
v1("1");
console.log(v1());
}
else if(value === "false") {
v1("2");
console.log(v1());
}
}
};
function ViewModel() {
this.test = ko.observable(false);
this.test2 = ko.observable("2");
};
$(function() {
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
})
Modify the update function for your needs. 根据需要修改更新功能。 You can add any number of variable to the binding with v1 : ... , v2 : ... , v3 : ... and access it via allBindingsAccessor().v1 , allBindingsAccessor().v2 , allBindingsAccessor().v3 您可以使用v1:...,v2:...,v3:...向绑定添加任意数量的变量,并通过allBindingsAccessor()。v1,allBindingsAccessor()。v2,allBindingsAccessor()。v3访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.