Reputation: 1527
I've recently tried using Backbone, and wanted to ask a basic question. This view is rendering as you'd expect:
(function($){
var ListView = Backbone.View.extend({
tagName: 'div',
el: $('header'),
initialize: function(){
_.bindAll(this, 'render');
this.render(); // not all views are self-rendering. This one is.
},
render: function(){
$(this.el).html("<ul> <li>hello world</li> </ul>");
}
});
var listView = new ListView();
})(jQuery);
My question is, why can't I just do without the initialize function and put this:
(function($){
var ListView = Backbone.View.extend({
tagName: 'div',
el: $('header'),
render: function(){
$(this.el).html("<ul> <li>hello world</li> </ul>");
}
});
this.render(); //No html is rendered on the page
var listView = new ListView();
})(jQuery);
I looked in the source code and the initialize function was an empty function by default, which took me be surprise. I sense the answer is quite straight forward, would appreciate the wisdom of a more experienced Backbone.js developer. Thanks!
Upvotes: 1
Views: 3417
Reputation: 20180
Try This
(function ($) {
var ListView = Backbone.View.extend({
tagName: 'div',
el: $('header'),
render: function () {
$(this.el).html("<ul> <li>hello world</li> </ul>");
}
});
var listView = new ListView();
// Call render on the view instance
listView.render();
})(jQuery);
Upvotes: 2
Reputation: 4844
I think the problem is that at the point you are calling this.render()
, 'this' is referring to the context of the module and not the Backbone View. If you refactor the code to remove the this.render()
line and add listView.render()
after the listView
instance has been created it should resolve the problem.
In summary, in this instance you don't need the initialize
function.
Upvotes: 2