LDK*_*LDK 48 backbone.js underscore.js
在backbone的todo演示中,代码中有一些_.bindAll(this,...)使用的地方.具体来说,它用于initialize两个视图的功能.据我所知,有必要做以下事情:
this.$('.todo-content').text(content);
Run Code Online (Sandbox Code Playgroud)
但是,当人们可以这样做时,为什么要做上述事情:
$('.todo-content').text(content);
Run Code Online (Sandbox Code Playgroud)
?
Geo*_*kin 93
_.bindAll( this, ... )不仅是必要的,this.$( selector ).doSomething()而且通常要确保this在您的视图中方法始终指向视图本身.
例如,如果我们想在模型更改时刷新视图,我们将视图的render方法绑定到模型的change事件:
initialize: function() {
this.model.bind( 'change', this.render );
},
Run Code Online (Sandbox Code Playgroud)
如果没有_.bindAll( this, 'render' ),当模型更改this时render将指向模型而不是视图,因此我们不会既没有this.el也没有this.$任何其他视图的属性.
Joh*_*ika 59
从Backbone 0.5.2开始,不再需要在视图中使用_.bindAll(this ...)来设置"bind"回调函数的上下文,因为您现在可以将第3个参数传递给bind()将设置回调的上下文(即"this").
例如:
var MyView = Backbone.View.extend({
initialize: function(){
this.model.bind('change', this.render, this);
},
render: function(){
// "this" is correctly set to the instance of MyView
}
});
Run Code Online (Sandbox Code Playgroud)
paw*_*lik 36
this.$ 将jQuery的上下文限制为视图的元素,因此操作更快.
另外,在视图元素之外的类中this.$('.todo-item') 不会找到您todo-item的元素.
| 归档时间: |
|
| 查看次数: |
20120 次 |
| 最近记录: |