为什么在backbone.js视图中使用bindAll?
在backbone的todo demo中,代码有几个地方_.bindAll(this, ...)
使用。具体来说,它在两个视图的 initialize
函数中使用。据我所知,有必要执行以下操作:
this.$('.todo-content').text(content);
但是,当人们可以执行以下操作时,为什么要执行上述操作:
$('.todo-content').text(content);
?
In backbone's todo demo the code has a few spots where _.bindAll(this,...)
is used. Specifically it's used in the initialize
function of both views. As far as I can tell it's necessary to do the following:
this.$('.todo-content').text(content);
But why would one want to do the above, when one can do:
$('.todo-content').text(content);
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
_.bindAll( this, ... )
不仅对于this.$(selector ).doSomething()
是必要的,而且通常是为了确保this<视图方法中的 /code> 始终指向视图本身。
例如,如果我们想在模型更改时刷新视图,我们将视图的
render
方法绑定到模型的change
事件:Without
_.bindAll( this , 'render' )
,当模型更改时,render
中的this
将指向模型,而不是视图,所以我们两者都不会this.el
也不是this.$
或任何其他可用的视图属性。_.bindAll( this, ... )
is necessary not only forthis.$( selector ).doSomething()
but generally to be sure thatthis
in your view's method is always pointing to the view itself.For example, if we want to refresh our view when the model changes, we bind the view's
render
method to the model'schange
event:Without
_.bindAll( this, 'render' )
, when the model changesthis
inrender
will be pointing to the model, not to the view, so we won't have neitherthis.el
northis.$
or any other view's properties available.从 Backbone 0.5.2 开始,不再需要在视图中使用 _.bindAll(this...) 来设置“绑定”回调函数的上下文,因为您现在可以将第三个参数传递给 bind()将设置回调的上下文(即“this”)。
例如:
As of Backbone 0.5.2, it's no longer necessary to use _.bindAll(this...) in your views to set the context of the "bind" callback functions, as you can now pass a 3rd argument to bind() that will set the context (i.e. "this") of the callback.
For example:
this.$
将 jQuery 的上下文限制为视图元素,因此操作速度更快。另外,
this.$('.todo-item')
不会在视图元素之外找到具有todo-item
类的元素。this.$
limits jQuery's context to the view's element, so operations are quicker.Additionaly,
this.$('.todo-item')
won't find your elements withtodo-item
class outside your view's element.