[英]Backbone/javascript - confused by 'this' keyword
In the following backbone scripts, I tried to change a collection in a view click event. 在以下主干脚本中,我尝试在视图单击事件中更改集合。
var StudentView = Backbone.View.extend({
initialize: function() {
console.log("create student items view");
this.collection.bind('add',this.render,this);
this.collection.bind('remove',this.render,this);
},
render : function(){
},
events :{
"click ":"select_students"
},
select_students: function(){
this.collection.reset([]);
_.each(students.models, function(m) {
if(m.get('name')=="Daniel"){
this.collection.add(m);
}
});
}
});
var students_view = new StudentView({el:$("#student_table"),collection:selected_students});
I got this error 我收到了这个错误
How should I call "this.collection" in the code? 我该如何在代码中调用“this.collection”?
You should change you select_students
to 您应该将select_students
更改为
select_students: function(){
var self = this;
this.collection.reset([]);
_.each(students.models, function(m) {
if(m.get('name')=="Daniel"){
self.collection.add(m);
}
});
}
The problem is that in JavaScript, the this
context is lost in inner functions (like the one you pass to _.each
) so the general pattern is to save a reference outside of that ( self
) and then use that in the inner function. 问题是在JavaScript中, this
上下文在内部函数中丢失(就像你传递给_.each
),所以一般模式是在( self
)之外保存一个引用,然后在内部函数中使用它。
Rather than using underscore's each() function, backbone collections can be iterated on directly, and can take a context to define what the 'this' variable refers to (passed as the second argument to each below). 而不是使用下划线的each()函数,骨干集合可以直接迭代,并且可以使用上下文来定义'this'变量引用的内容(作为第二个参数传递给下面的每个)。
So the best way to do this is to: 所以最好的方法是:
select_students: function(){
this.collection.reset([]);
students.each(function(m) {
if(m.get('name')=="Daniel"){
this.collection.add(m);
}
}, this);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.