简体   繁体   中英

Toggle values in observableArray Knockout JS?

Basically I have a list and each item in the list has a unique value. If a list item is clicked on, I want the value to be added or removed from an observable array. So if that value exists in the array, I want to remove it and vice-versa.

The structure of the array would be simple:

var items = ko.observableArray([
    "value1",
    "value2"
]);

The list will have inputs with value1 and value2 . If the list with value2 is clicked on, I want to remove it from the array, and if it doesn't, I need to push it to the array.

So basically I need to toggle an item in the array.

Is this possible with knockout.js? Thanks!

Sure. Knockout's observableArray has an indexOf method built right in. Use it, along with push and remove to do what you're asking. Something like this should work:

function toggle(value){
    if (items.indexOf(value) < 0){
        //it's not in the array - push it
        items.push(value);
    } else {
        //it's there - remove it
        items.remove(value);
    }
}

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