1
我有幾個模型,它們可以獲取自己的url/api。具有多個不同模型類別的飼料主幹集合
我想將它們保存在一個集合中。
- 聽起來像個好主意嗎?
- 你將如何獲取它們? (我想只是爲了讓我想從集合中更新模型然後獲取它)
讓我知道你的想法,如果你有任何理論上的閱讀/建議。
我有幾個模型,它們可以獲取自己的url/api。具有多個不同模型類別的飼料主幹集合
我想將它們保存在一個集合中。
讓我知道你的想法,如果你有任何理論上的閱讀/建議。
集合可以包含任何原始對象或從Backbone.Model
派生的任何模型。只有當你有一個返回一個對象數組的API端點時,獲取一個集合纔有意義。
如果您想要獲取特定的模型,可以保留對它的引用,或者只將其存儲在集合中,然後在其上調用fetch
。
碰撞時可能會導致問題,其中相同的id被視爲相同的模型併合並在一起。
var book = new Book({ id: 1, title: "My Book" }),
note = new Note({ id: 1, title: "note test" });
var collection = new Backbone.Collection([book, note]);
console.log(collection.length); // 1
方法,以避免碰撞id
:
一種製作多模型集合的方法是使用model
property作爲函數。儘管默認情況下它不會阻止id
衝突。
var BooksAndNotes = Backbone.Collection.extend({
/**
* Different models based on the 'type' attribute.
* @param {Object} attrs currently added model data
* @param {Object} options
* @param {Backbone.Model} subclass dependant of the 'type' attribute.
*/
model: function ModelFactory(attrs, options) {
switch (attrs.type) {
case "book":
return new Book(attrs, options);
case "note":
return new MTextSession(attrs, options);
default:
return new Backbone.Model(attrs, options);
}
},
// fixes this.model.prototype.idAttribute and avoids duplicates
modelId: function(attrs) {
return attrs.id;
},
});
var collection = new BooksAndNotes([{
title: "My Book",
type: 'book'
}, {
title: "note test",
type: 'note'
}]);
查看關於多個模型的集合,在類似的問題:
的可能的複製(HTTP [骨幹多了Collection?]://計算器.COM /問題/ 14263765 /骨幹網收集與 - 多型號) –