2

我正在使用 knockout.js 库。我正在尝试使用敲除arrayRemoveItem实用程序功能,但它似乎不起作用。这是我的代码:

JS

function VM()
{
  this.Items = [{id:'1', name:'A'}, 
                {id:'2', name:'B'}, 
                {id:'3', name:'C'}, 
                {id:'4', name:'D'}
               ];

  this.Delete = function(){
    console.log(this.Items);          //before removing

    ko.utils.arrayRemoveItem(this.Items, function(item){
      return item.id == '3';
    });

    console.log(this.Items);          //after removing
  };
}

小提琴

如果您在按下删除按钮后检查控制台,则项目 3 不会从阵列中删除。我在这里缺少什么?

4

1 回答 1

8

arrayRemoveItem要删除的项目作为第二个参数ko.utils.arrayRemoveItem(array, itemToRemove),因此您需要首先找到对象并将其传递给arrayRemoveItem.

尝试

function VM()
{
  this.Items = [{id:'1', name:'A'}, 
                {id:'2', name:'B'}, 
                {id:'3', name:'C'}, 
                {id:'4', name:'D'}
               ];

  this.Delete = function(){

    var item;
    ko.utils.arrayForEach(this.Items, function(v) {
      if(v.id == '3'){
        item = v;
      }
    });

    console.log(this.Items);
    ko.utils.arrayRemoveItem(this.Items, item);
    console.log(this.Items);
  };
}

ko.applyBindings(new VM());

演示:小提琴

于 2013-03-23T04:11:45.873 回答