【问题标题】:knockoutjs when checked data binding call function敲除js时检查数据绑定调用函数
【发布时间】:2013-06-23 06:28:39
【问题描述】:
我需要做以下事情:当用户选中复选框时,会调用一些函数。
<input type="checkbox" data-bind="what to write here?" />
在模型中:
var viewModel = {
this.someFunction = function() {
console.log("1");
}
};
我没有找到任何关于此的文档 here。
【问题讨论】:
标签:
javascript
data-binding
knockout.js
【解决方案1】:
你需要的是click binding:
<input type="checkbox" data-bind="click: someFunction" />
在你的视图模型中:
var ViewModel = function(data, event) {
this.someFunction = function() {
console.log(event.target.checked); // log out the current state
console.log("1");
return true; // to trigger the browser default behavior
}
};
演示JSFiddle.
或者,如果您想使用 checked 绑定,您可以订阅您的属性的更改事件:
<input type="checkbox" data-bind="checked: isChecked" />
在您的视图模型中:
var ViewModel = function() {
this.isChecked = ko.observable();
this.isChecked.subscribe(function(newValue){
this.someFunction(newValue);
}, this);
this.someFunction = function(value) {
console.log(value); // log out the current state
console.log("1");
}
};
演示JSFiddle.
【讨论】:
-
-
当使用 subscribe 时,您将获得以下值:this.isChecked.subscribe(function(newValue){ 参见 jsfiddle.net/qx8DC/1,在点击绑定情况下,您可以使用 this.someFunction = function(data,event) { console.log(event.target.checked); 获得值,参见:jsfiddle.net/GH2tJ/1