javascript Knockout JS - 数据绑定多个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11371138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Knockout JS - data-bind multiple values
提问by user1436111
Question about JS Knockout library - I have three inputs, all data-Bind-ed to the same variable. Two have a boolean value of false and one has a boolean value of 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.
关于 JS Knockout 库的问题 - 我有三个输入,所有数据都绑定到同一个变量。两个的布尔值为 false,一个的布尔值为 true。(不幸的是,我无法将它们更改为整数,这会使这个问题更容易)。尽管这两个假值输入共享行为,但我需要以某种方式区分它们以触发略有不同的行为。
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.
我直接试过了,没有用,所以我不知道是否可能。非常感谢。
采纳答案by Luffy
You cant bind multiple variables directly but creating a custom bind function do the trick for you.
您不能直接绑定多个变量,但是创建自定义绑定函数可以为您解决问题。
Example : http://jsfiddle.net/gurkavcu/ePW8Y/
** Change input value (true , false) to trigger the update function
示例:http: //jsfiddle.net/gurkavcu/ePW8Y/
** 更改输入值 (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 访问它