简体   繁体   中英

Removal of item from ko.observableArray

I want to remove an object from an ko.observableArray I have two observableArrays

self.arrayA = ko.observableArray();
self.arrayB = ko.observableArray();

then in a function I want to remove an item.

self.myRemoval = function(item){
    var arrayToRemoveFrom;
    if ( somelogic ) {
        arrayToRemoveFrom = self.arrayA();  
    }
    else {
        arrayToRemoveFrom = self.arrayB(); 
    }
    arrayToRemoveFrom.remove(item);   
} 

The line "arrayToRemoveFrom.remove(item)" causes an exception, saying remove is not a function. What would be the best way to remove "item"?

remove is a special function of the ko.onservableArray .

However when you write self.arrayA(); with the () at the end you are returning the underlaying JavaScript array which does not have a remove function and you get the exception.

To fix your code you just need to remove the () :

self.myRemoval = function(item){
    var arrayToRemoveFrom;
    if ( somelogic ) {
        arrayToRemoveFrom = self.arrayA;  
    }
    else {
        arrayToRemoveFrom = self.arrayB; 
    }
    arrayToRemoveFrom.remove(item);   
} 

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