I’m following a backbone.js tutorial and came across 2 functions initialize() and render(). initialize() used $(self.el).append() when appending some html while render() used $(this.el).append(). I am confused about the difference, would appreciate an explaination, thanks!
JS Code
// Views
window.WineListView = Backbone.View.extend({
tagName:'ul',
initialize:function () {
this.model.bind("reset", this.render, this);
var self = this;
this.model.bind("add", function (wine) {
$(self.el).append(new WineListItemView({model:wine}).render().el);
});
},
render:function (eventName) {
_.each(this.model.models, function (wine) {
$(this.el).append(new WineListItemView({model:wine}).render().el);
}, this);
return this;
}
});
The first uses
selfto keep a reference tothiswhen the scope changes when the event fires. Inside the anonymous function (for the event handler),thiswould refer to the element that fired the event rather than your Backbone controller.The reference isn’t needed in the second case.