Binding and _.bindAll in backbone.js

不羁岁月 提交于 2019-12-05 16:40:33

phew--long question(s) ;)

1) I used to do _.bindAll in my initialize methods when I was first using backbone but I have since stopped. It's not normally needed unless you're binding to events and then it's really helpful. For example if you have:

events:
{
    'click': clickHandler
},
clickHandler: function(){
    //do cool stuff
}

then it's helpful to do _.bindAll(this, 'clickHandler') otherwise your this pointer won't be the view

2) If i understand your question: commentList becomes a property of your instance of ModalView.

3) using var self = this; is relatively common, but in many cases can be avoided because of overloads in Underscore.js (which is a dependency of backbone.js). For instance, most of the collection functions (map, each, etc) take a context as the last parameter. so instead of

var self = this;
_.map([1,2], function(item){
    self.sum = self.sum + item; 
});

you can do:

_.map([1,2], function(item){
    this.sum = this.sum + item; 
}, this);

if your case you could replace your success method with

success: _.bind(function() {
             this.commentListView = new CommentListView({ collection: this.commentList });
         }, this);

If you want more info on the somewhat confusing subject of this pointers, it's suggest the following excellent tutorial: http://bonsaiden.github.com/JavaScript-Garden/#function.this

4) Yes--I would move the rendering to the reset. that way if something else causes a reset of the collection the view will pick it up.

Hope I answered all your questions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!