Backbone.js将此绑定到$ .each

我正在使用backbonejs并在我拥有的方法中:

$.each(response.error, function(index, item) { this.$el.find('.error').show(); }); 

但是,因为它是$.eachthis.$el是未定义的。

我有_.bindAll(this, 'methodName') ,它将在每个之外工作。 那么,现在我需要绑定它吗?

任何帮助都会很棒! 谢谢

你正在使用Backbone所以你有_.each ,这意味着你有_.each

每个 _.each(list, iterator, [context])

迭代一个元素列表 ,依次产生一个迭代器函数。 迭代器绑定到上下文对象(如果传递了一个)。

所以你可以这样做:

 _.each(response.error, function(item, index) { this.$el.find('.error').show(); }, this); 

或者你可以使用_.bind

 $.each(response.error, _.bind(function(index, item) { this.$el.find('.error').show(); }, this)); 

或者,既然你一遍又一遍地发现同样的事情,那就预先计算并停止关心this

 var $error = this.$el.find('.error'); $.each(response.error, function(index, item) { $error.show(); }); 

这是两个Underscore方法的快速演示: http : //jsfiddle.net/ambiguous/dNgEa/

在循环之前设置局部变量:

 var self = this; $.each(response.error, function(index, item) { self.$el.find('.error').show(); });