Since Collections is actually a model, it has attributes and so on, like in this example
var Images = Backbone.Collection.extend({
url: 'https://api.myjson.com/bins/4v2d8'
});
var View = Backbone.View.extend({
el: $('.images'),
initialize: function(){
this.listenTo(this.collection, 'sync', this.render, this); // what is this keyword as the last param here?
},
render: function(){
this.collection.each(function(model){
this.$el.append($('<p>'+model.get('name')+'</>' ));
}, this);
}
});
$(function(){
var images = new View({ collection: new Images() });
images.collection.fetch();
});
http://jsbin.com/gohedeguto/edit?html,js,output
But why this one doesn't work?
http://jsbin.com/seyoyeqeku/edit?html,js,output
I replaced Collection
with Model
and passed to the View. I got this.model.each of undefined
.
Since Collections is actually a model
No. This is wrong assumption. Collection is not a model which is why your code doesn't work.
Model does not have an each method and your code throws following error:
Uncaught TypeError: this.model.each is not a function(…)
and don't follow the other answer that iterates over model properties and prints it's name, it doesn't make sense. Because model is supposed to represent an entity, like a person. It'll only have one property containing name, there's no point in iterating over model properties to access one of them, you can directly access it's attributes with get()
method without having to iterate.
While T-J is right, he doesn't elaborate on why.
A Backbone model has lots of functions to manage an attributes
hash, and is often referenced by an id.
A Backbone collection is an array of Backbone model instances. It has some similar and lots of different functions to manage its models
array property which is where the model instances are stored.
Some of these functions are proxies to Underscore.js functions.
Model's Underscore methods
- keys
- values
- pairs
- invert
- pick
- omit
- chain
- isEmpty
Collection's Underscore methods
46 in total at the moment, see the list.
collection.each(iteratee, [context])
is a proxy to _.each(collection.models, iteratee, [context])
.
Backbone's Model do not have a each
function because it doesn't really make sense and there are better ways to loop through the attributes of a model.