从Backbone集合中过滤模型时维护索引

时间:2016-06-30 22:19:39

标签: javascript backbone.js

我有一个集合

var Book = Backbone.Model.extend({
    defaults:{
       name: '',
       author: ''
    }
});

var BookCollection = Backbone.Collection.extend({
     model: Book
});


/*** Populate the Collection ***/

var b1 = new Book({name: 'Java programming', author: 'John Doe'});
var b2 = new Book({name: 'C# programming', author: 'Alice Jane'});
var b3 = new Book({name: 'SQL in depth', author: 'James Wayne'});

var bkCollection = new BookCollection();

bkCollection.push(b1);
bkCollection.push(b2);
bkCollection.push(b3);

//I want to remove all models where name contains word 'programming'

var RESTRICTED = 'programming';

bkCollection.each(function(book){
    if(book.get('name').indexOf(RESTRICTED) > -1){
        bkCollection.remove(book);
    }
});

然而,当有大量记录(> 100)时,我最终得到了未定义的模型和编程标题

从Backbone中的集合中过滤掉模型的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

bkCollection.remove(book);正在迭代它时从集合中删除模型。而是将模型推入数组,然后从集合中删除。

var Book = Backbone.Model.extend({
    defaults:{
       name: '',
       author: ''
    }
});

var BookCollection = Backbone.Collection.extend({
     model: Book
});


/*** Populate the Collection ***/

var b1 = new Book({name: 'Java programming', author: 'John Doe'});
var b2 = new Book({name: 'C# programming', author: 'Alice Jane'});
var b3 = new Book({name: 'SQL in depth', author: 'James Wayne'});

var bkCollection = new BookCollection();

bkCollection.push(b1);
bkCollection.push(b2);
bkCollection.push(b3);

//I want to remove all models where name contains word 'programming'

var RESTRICTED = 'programming';

var booksToRemove = new Array(); //cfa: the array that will hold the books to be removed
bkCollection.each(function(book){
    if((book.get('name').indexOf(RESTRICTED)) > -1){
        booksToRemove.push(book); // cfa: push the model into the array
    }
});

bkCollection.remove(booksToRemove); // remove from collection

console.log('Updated Collection is ' + JSON.stringify(bkCollection));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>

答案 1 :(得分:0)

问题是在迭代过程中删除模型,正如bvoleti已经提到的那样。您可以使用内置方法(例如filter代替each

)轻松解决此问题
var RESTRICTED = 'programming';
var matches = bkCollection.filter(function(book){
  return book.get('name').indexOf(RESTRICTED) > -1;
});
bkCollection.remove(matches);