我对绑定及其目的感到困惑_bind.All
在backbone.js中。下面是创建模态视图的工作代码#modal
并渲染从后端获取的评论。
首先,在下面的代码中,我在initialize
功能_.bindAll(this, 'render', 'renderComments');
。不管我做与不做_.bindAll()
, 我打电话没有问题this.render()
and this.renderComments()
inside initialize()
。有没有什么时候的例子_.bindAll()
会帮助我们,什么时候不会?
ModalView = Backbone.View.extend({
el: $('#modal'),
template: _.template( $('#tpl_modal').html() ),
initialize: function() {
_.bindAll(this, 'render', 'renderComments');
this.render();
this.renderComments();
},
render: function() {
$(this.el).fadeIn('fast').append( this.template( this.model.toJSON( this.model ) ) );
},
renderComments: function() {
this.commentList = new CommentCollection();
var self = this;
this.commentList.fetch({
data: { post_id: this.model.id},
processData: true,
success: function() {
self.commentListView = new CommentListView({ collection: self.commentList });
}
});
}
});
And
CommentListView = Backbone.View.extend({
el: '.modal_comments',
initialize: function() {
this.render();
},
render: function() {
var self = this;
this.collection.each( function(comment, index) {
$(self.el).append( new CommentListItemView({ model: comment }).render().el );
});
return this;
}
});
其次,我对前置感到困惑this.
对某事。例如在renderComments
,为什么我不能使用:
var commentList = new CommentCollection();
var self = this;
commentList.fetch({.... });
对于线路this.commentList = new CommentCollection();
,除了实例化类之外CommentCollection()
,它是否使commentList
的孩子ModalView
?
另外,是否需要有var self = this;
并使用self.commentListView
稍后在回调函数中?可以使用绑定以便我可以访问吗this.commentListView
,或者正在使用var self = this
传统的做事方式?
最后,应该self.commentListView = new CommentListView({ collection: self.commentList });
在成功函数中renderComments
被移至CommentListView
的初始化方法代替并绑定到this.collection.on('reset');
防止嵌套太多函数?这将导致:
ModalView = Backbone.View.extend({
el: $('#modal'),
template: _.template( $('#tpl_modal').html() ),
initialize: function() {
_.bindAll(this, 'render', 'renderComments');
this.render();
this.renderComments();
},
render: function() {
$(this.el).fadeIn('fast').append( this.template( this.model.toJSON( this.model ) ) );
},
renderComments: function() {
this.commentList = new CommentCollection();
this.commentListView = new CommentListView({ collection: this.commentList });
this.commentList.fetch({
data: { post_id: this.model.id},
processData: true
});
}
});
CommentListView = Backbone.View.extend({
el: '.modal_comments',
initialize: function() {
this.collection.on('reset', this.render, this);
},
render: function() {
var self = this;
this.collection.each( function(comment, index) {
$(self.el).append( new CommentListItemView({ model: comment }).render().el );
});
return this;
}
});