I am trying to build a collection, but need to build it dynamically as i don’t know how many to be pushed. Currently what I do is;
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);
Instead of manually saying
link1 = new dataModel({ dataID: "1", text: "1" });
myDataCollection.push(link1);
can I create the list this dynamically..
For example, if i have 4 links, I want link4 to be added with dataID: 4, TextID: 4… etc…
If you need to populate collection while initialization, you can simply pass an array of objects to populate, there is no need to create a model for each object, Backbone.Collection will do it for you: