简体   繁体   中英

Knockout js observable arrays and checkbox, checked bind fail

I'm trying to figure out why the text entry field is not active when the checkbox changes?

<form data-bind="foreach: editables">
    <input type="checkbox" name="edit" data-bind=" checked: active" />
    <input type="text" name="edit" data-bind="value: name, disable: !active" />
    <br/>
</form>

var viewModel = function () {
   this.editables = ko.observableArray(
[{
    active: true,
    name: "mi"
}, {
    active: false,
    name: "yo"
}, {
    active: true,
    name: "cel"
}]);
};

ko.applyBindings(new viewModel());

http://jsfiddle.net/legolito/2FAJN/2/

I hope that someone can helpme. (english isn't my native language, so i'm sorry if something is bad with my grammar )

Have you considered making the active property an observable ?

http://jsfiddle.net/tzG3t/

var viewModel = function () {
    this.editables = ko.observableArray(
    [{
        active: ko.observable(true),
        name: "mi"
    }, {
        active: ko.observable(false),
        name: "yo"
    }, {
        active: ko.observable(true),
        name: "cel"
    }]);
};

ko.applyBindings(new viewModel());

That because you are not using ko.observable in ko.observableArray

See the knockout documentation on observableArrays

Key point: An observableArray tracks which objects are in the array, not the state of those objects

Simply putting an object into an observableArray doesn't make all of that object's properties themselves observable. Of course, you can make those properties observable if you wish, but that's an independent choice. An observableArray just tracks which objects it holds, and notifies listeners when objects are added or removed.

So make it observable and problem solved.
Fiddle: http://jsfiddle.net/2FAJN/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM