I am(as a beginner) making a small backbone function to append my links, for this i using the collection to be assigned model,
But the collection throw the error.. any one can correct my code please?
$(function(){
var Model = new Backbone.Model({
data:[
{name:'Yahoo',href:'http://www.yahoo.com'},
{name:'Gmail',href:'http://www.gmail.com'},
{name:'Bing',href:'http://www.bing.com'}
]
});
var Collection = new Backbone.Collection.extend({
model:Model // is this not correct way to do?
});
var View = Backbone.View.extend({
el:'#container',
events:{
'click button':'render'
},
initialize:function(){
this.collection = new Collection(); //throw the error!
this.template = $('#temp').children();
},
render:function(){
var data = this.collection.get('data');
for(i=0;i<data.length;i++){
var li = this.template.clone().find('a')
.attr('href',data[i].href)
.text(data[i].name).end();
this.$el.find('ul').append(li);
}
}
});
var myLink = new View();
})
Models are used to store and manage individual chunks of data. In your case that would be a single name/href pair. Usually you use
Backbone.Model.extendto create a model “class” with all your model-specific methods and properties and then you create instances of that model withnewor set that model “class” as a collection’smodelproperty so that the collection can create new instances of the model.Your model should look more like this:
Notice that there’s no
newin there as we’re just making a “class” to base our model instances on. Then we hook the model up to a collection (again usingextendwith nonew):Now you can create an instance of the collection and hand it an array of data for the models:
You’ll often pass the collection to the view rather than making the view instantiate the collection; Backbone will automatically set
this.collectionif you saynew SomeView({ collection: some_collection })so you can:and say
new View({ collection: links })and access the collection throughthis.collectionelsewhere in the view.A collection is a collection of several models (sort of like an array) and it will have various useful Underscore methods mixed in so you can iterate through the collection like this:
Also notice the use of
getto access model attributes, model attributes and object properties are different things. You can also usetoJSONto flatten all the data at once. The finalthisargument toeachmakesthisinside the callback the view. Backbone already supplies athis.$el.find()alias in the view’sthis.$()method so I switch to that as well.Here’s a simplified demo: http://jsfiddle.net/ambiguous/WSqLM/