Jinny Song Jinny Song - 6 months ago 19
Javascript Question

Why people formally do this.$el.html() in the very first line of backbone view rendering?

There's a Backbone.js view render function below:

var bookListView = Backbone.View.extend({
model: BooksCollection,

render: function() {
this.$el.html(); // lets render this view

var self = this;

for (var i = 0; i < this.model.length; ++i) {
// lets create a book view to render
var m_bookView = new bookView({
model: this.model.at(i)
});

// lets add this book view to this list view
this.$el.append(m_bookView.$el);
m_bookView.render(); // lets render the book
}

return this;
},
});


I just came to know that people usually add
this.$el.html();
at the begining of the render function for rendering the view.

However, I have no idea why this code is used on the first line. It just works totally same, even though I remove the first line.

T J T J
Answer

That line you usually see is this.$el.html('');. Note the extra '' which makes it a setter, rather than getter. It is used to clear the existing content in the view similar to this.$el.empty(). If it is not there, when you re-render the view to display changed data, the old data will stay in it, since it is a collection view to which items are just appended.

In the context of this particular example, let's say you have 2 books now and if the data changes to 3 books, you re-render this view - you'll have 5 books in it without the suspicious line.

As it is this.$el.html(); doesn't do anything in the code you shared, but this.$el.html(''); fixes a potential bug. I think you missed ''