简体   繁体   中英

Backbone.js initialize function - why do I need it?

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!

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM