knockoutjs checked binding

大憨熊 提交于 2019-12-23 18:34:02

问题


I am having trouble with the checked binding: clicking on the checkbox doesn't update the visible status, although a dependentObservable indicates that the value has changed.

Here is the HTML fragment:

<input type="checkbox" 
        data-bind="checked: document().selected" 
        title="Select one or more documents to find more similar ones" >

This is bound to an instance of my Posting class that has a document() observable. The relevant part of the document class looks like this:

function Document(data, topic) {
    this.id = ko.observable(data.id);
    this.url = ko.observable(data.url);
    this.title = ko.observable(data.title);

    /** Display state **/
    this.selected = ko.observable(false);
    ko.dependentObservable(function() {
        console.log("Selected " + this.url() + " : " + this.selected());
    }, this);

}

When I click on the check box, the console prints something like this:

Selected http://somedomain.com/doc1.pdf : true

and yet the checkbox remains unchecked.

I am using jQuery 1.4.2 and knockout 1.2.1

Other aspects of knockout seem to be working correctly. When I isolated the problem in jsffiddle like this, it worked as expected. Any thoughts on what I should test next?

Gene

UPDATE: Dec 12, 2011 2:54 PST:

@RP Niemeyer: I have many other dependentObservable instances; the only one that metnions selected() looks like this:

this.selectedDocuments = ko.dependentObservable( function() {
    return this.documents().findAll(function(doc) {return doc.selected()});
}, this);

findAll does what you mighht think.

As far as I can tell, what's happening is that the selected observable is set to true when the checkbox is triggered, which fires the dependentObservable, which prints the correct value. The view is not updated, however. Nonetheless, the observable thinks it's set to true, because subsequent clicks on the same (deselected) checkbox do not produce any further console output.

UPDATE Dec 12, 2011, 9:45 PM PST:

I was able to reproduce the problem in this jsfiddle. If you edit out the click handler on the enclosing div, the checkboxes work correctly. Is there a work-around, or is this a known problem?


回答1:


OK- with the updates it makes sense. What you can do is return true; from the click handler that is on the outside div. This will allow the default action to proceed.

http://jsfiddle.net/rniemeyer/SbuEV/8/



来源:https://stackoverflow.com/questions/8481015/knockoutjs-checked-binding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!