Reputation: 137
This is probably more of a javascript question, but I'm going through this backbone tutorial and was wondering why is there a .$el at the end of this line, and which element is it point to?
self.$el.append((new BlogView({ model: blog})).render().$el);
Here is the full code below.....
var BlogsView = Backbone.View.extend({
model: blogs,
el: $('.blogs-list'),
initialize: function() {
this.model.on('add', this.render, this);
},
render: function() {
var self = this;
this.$el.html('');
_.each(this.model.toArray(), function(blog) {
self.$el.append((new BlogView({ model: blog})).render().$el);
});
return this;
}
});
Upvotes: 0
Views: 208
Reputation: 13409
$el
is a reference for the DOM element for the view. Backbone views are not DOM elements themselves, they are generic javascript objects which have a property called $el
which holds the DOM element which is what you actually see on the webpage. You can think of a backbone view as a controller of sorts for the DOM element, and when you add event listeners to your view, define render, etc, you are always acting on its DOM element stored in $el
($el
is the same DOM element as el
, the former just plays nicely with jQuery). In this case, your view is BlogView
and if we break new BlogView({ model: blog})).render().$el
up:
new BlogView
- creating an instance of your view, backbone will automatically create a DOM element for your view and store it in yourView.$el
.render()
- telling the view to render its HTML inside the $el
element. In Backbone, our render function is where we generate HTML markup/format data and "draw" the view by shoving this markup into our view's $el
.
render().$el
- render()
returns this
which is just our view itself, so calling render().$el
is like saying "render my view and return my DOM element.
self.$el.append(..)
- this block of code is thus given our DOM element $el
which then inserts it.
so putting it all together we get: new BlogView({ model: blog})).render().$el
which first creates our view, renders our view and returns our view's DOM element which can be appended to the page, manipulated, etc.
Upvotes: 2