简体   繁体   中英

Observable array and computed error

I have a list of checkboxes that execute functions on check and uncheck. I also have an observable array that holds the values of the checkboxes currently active (put into local storage). The relevant code is here:

this.layerToggleChecked = knockout.observableArray();

// ...

this.layerToggle = function (source, name, type, url, description) {
    return knockout.computed({
        read: function () {
            return this.layerToggleChecked();
        },
        write: function (checked) {
            if (checked) {
                alert("loading");
                this.layerToggleChecked.push(source());
            } else {
                alert("removing");
                this.layerToggleChecked.remove(source());
            }
        }
    }, this);
}

The checkboxes work as planned triggering the functions until I added return this.layerToggleChecked(); which returns

knockout-3.2.0.js:13 Uncaught TypeError: b.push is not a function

Knockout's checked binding handles arrays differently from other values. You're expecting a true or false to be written to the computed observable, but you're returning an array, which obviously aren't the same.

From http://knockoutjs.com/documentation/checked-binding.html :

Special consideration is given if your parameter resolves to an array . In this case, KO will set the element to be checked if the value matches an item in the array, and unchecked if it is not contained in the array.

When the user checks or unchecks the checkbox, KO will add or remove the value from the array accordingly.

Since you're using an array to hold the checked values, you're better off binding directly to it:

<input type="checkbox" data-bind="checkedValue: source, checked: layerToggleChecked" />

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