2016-06-30 34 views
0

濾鏡模式我有一個集合作爲保持索引而從骨幹網收集

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中從集合中過濾出模型的正確方法是什麼?

回答

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>

0

問題作爲bvoleti已經提到的迭代過程中去除模型。您可以使用內置方法如filter而不是each輕鬆修復此問題:

var RESTRICTED = 'programming'; 
var matches = bkCollection.filter(function(book){ 
    return book.get('name').indexOf(RESTRICTED) > -1; 
}); 
bkCollection.remove(matches);