knockoutjs检查数据绑定调用函数时

5 javascript data-binding knockout.js

我需要做以下事情:当用户选中复选框时,会调用某些函数.

<input type="checkbox" data-bind="what to write here?" />
Run Code Online (Sandbox Code Playgroud)

在模型中:

var viewModel = {
    this.someFunction = function() {
       console.log("1");
    }
};
Run Code Online (Sandbox Code Playgroud)

我还没有发现任何关于这个文件在这里.

nem*_*esv 17

你需要的是click绑定:

<input type="checkbox" data-bind="click: someFunction" />
Run Code Online (Sandbox Code Playgroud)

在您的视图模型中:

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  
    }
};
Run Code Online (Sandbox Code Playgroud)

演示JSFiddle.

或者,如果您想使用checked绑定,您可以订阅属性的更改事件:

<input type="checkbox" data-bind="checked: isChecked" />
Run Code Online (Sandbox Code Playgroud)

并在您的viewmodel中:

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");
    }
};
Run Code Online (Sandbox Code Playgroud)

演示JSFiddle.