最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - knockoutjs when checked data binding call function - Stack Overflow

programmeradmin7浏览0评论

I need to do following things: When user checks the checkbox, some function is called.

<input type="checkbox" data-bind="what to write here?" />

and in model:

var viewModel = {
    this.someFunction = function() {
       console.log("1");
    }
};

I have not found anything about this is documentation here.

I need to do following things: When user checks the checkbox, some function is called.

<input type="checkbox" data-bind="what to write here?" />

and in model:

var viewModel = {
    this.someFunction = function() {
       console.log("1");
    }
};

I have not found anything about this is documentation here.

Share Improve this question asked Jun 26, 2013 at 7:59 user721588user721588
Add a ment  | 

1 Answer 1

Reset to default 21

What you need is the click binding:

<input type="checkbox" data-bind="click: someFunction" />

And in your view model:

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  
    }
};

Demo JSFiddle.

Or if you want to you use the checked binding you can subscribe on the change event of your property:

<input type="checkbox" data-bind="checked: isChecked" />

And in your 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");
    }
};

Demo JSFiddle.

发布评论

评论列表(0)

  1. 暂无评论