2012-04-27 36 views
1

我使用backbonejs和方法裏面,我有:

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

然而,因爲它是在$.eachthis.$el是不確定的。

我有​​這將工作在每個之外。那麼,現在我需要將它綁定在內?

任何幫助都會很棒!謝謝

+0

Ack。我只是重讀這個問題,這不是我發佈的那個問題。無視這一點。抱歉。 – 2012-04-27 16:13:13

回答

10

您使用的骨幹,所以你有下劃線,這意味着,你必須_.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(); 
}); 

下面是兩種下劃線方法的快速演示:http://jsfiddle.net/ambiguous/dNgEa/

+0

太棒了,謝謝! – dzm 2012-05-01 18:38:52

2

設置局部變量循環之前:

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

夠簡單......謝謝:) – dzm 2012-04-27 16:27:00