2013-08-02 85 views
2

幫幫我。 如何通過id從Collection中獲取模型?如何通過id從Collection中獲取模型?

var Sidebar = Backbone.Model.extend({}); 
var sidebar = new Sidebar; 
var Library = Backbone.Collection.extend({}) 
lib=new Library(); 

lib.add(sidebar,{at: 234}); 

console.log(lib.get(234))//undefined ..Why?? 

回答

4

您似乎在混合idindex,這是不可互換的。

要通過id檢索,你會想與Model設置:

var sidebar = new Sidebar({ id: 234 }); 

// ... 

console.log(lib.get(234)); 

index是集合中的位置:

lib.add(sidebar, { at: 0 }); 

console.log(lib.at(0));  // sidebar 
console.log(lib.models); // Array: [ sidebar ] 
console.log(lib.models[0]); // sidebar 
+0

作品! !謝謝 –

0

試試這個

var Sidebar = Backbone.Model.extend({ 
    // Need to set this. Otherwise the model 
    // does not know what propert is it's id 
    idAttribute : 'at' 
}); 
var sidebar = new Sidebar(); 
var Library = Backbone.Collection.extend({}) 
var lib=new Library(); 

// Set the Model 
sidebar.set({at:234}); 

// Add it to the collection 
lib.add(sidebar); 

console.log(lib.get(234)) 

Check Fiddle

你加入收藏will be spliced at that index的方式和指標在插入模型。我不認爲這不是你想要的。因此,您需要先將屬性設置爲模型,然後將其添加到集合中。

相關問題