我正在尝试构建一个集合,但需要动态构建它,因为我不知道要推送多少集合。目前我所做的是;
var DataCollection = Backbone.Collection.extend({
model : dataModel
});
var dataModel = Backbone.Model.extend({
defaults : {
dataID : 'unknown',
text : 'unknown',
}
});
var linkPrev = new dataModel({ dataID: "Prev", text: "Prev" });
var link1 = new dataModel({ dataID: "1", text: "1" });
var link2 = new dataModel({ dataID: "2", text: "2" });
var link3 = new dataModel({ dataID: "3", text: "3" });
var linkNext = new dataModel({ dataID: "Next", text: "Next" });
var myDataCollection = new DataCollection();
//myDataCollection.push(linkPrev);
myDataCollection.push(link1);
myDataCollection.push(link2);
myDataCollection.push(link3);
myDataCollection.push(linkNext);
而不是手动说
link1 = new dataModel({ dataID: "1", text: "1" });
myDataCollection.push(link1);
我可以动态创建这个列表吗。
例如,如果我有4个链接,我希望link4添加dataID:4,TextID:4 ...等...
答案 0 :(得分:2)
如果你需要在初始化时填充集合,你可以简单地传递一个对象数组来填充,不需要为每个对象创建一个模型,Backbone.Collection会为你做这个:
var DataCollection = Backbone.Collection.extend({
model : DataModel
});
var DataModel = Backbone.Model.extend({
defaults : {
dataID : 'unknown',
text : 'unknown'
}
});
var myDataCollection = new DataCollection([
{ dataID: "Prev", text: "Prev" },
{ dataID: "1", text: "1" },
{ dataID: "2", text: "2" },
{ dataID: "3", text: "3" },
{ dataID: "Next", text: "Next" }
]);