Backbone.js将此绑定到$ .each [英] Backbone.js bind this to $.each

查看:96
本文介绍了Backbone.js将此绑定到$ .each的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是ribsjs,并且在我拥有的方法中:

I'm using backbonejs and inside a method I have:

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

但是,由于它位于$.each中,因此未定义this.$el.

However, because it's in $.each, this.$el is undefined.

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

I have _.bindAll(this, 'methodName') which will work outside of the each. So, now I need to bind it within?

任何帮助都会很棒!谢谢

Any help woudl be great! Thank you

推荐答案

您正在使用Backbone,因此您具有Underscore,这意味着您具有 _.each :

You're using Backbone so you have Underscore and that means that you have _.each:

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

遍历元素的列表,依次将每个元素赋予 iterator 函数.如果传递了 iterator ,则将其绑定到 context 对象.

Iterates over a list of elements, yielding each in turn to an iterator function. The iterator is bound to the context object, if one is passed.

所以您可以这样做:

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

或者您可以使用 _.bind :

Or you could use _.bind:

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

或者,由于您一次又一次地发现同一件事,因此请预先计算并停止关心this:

Or, since you're finding the same thing over and over again, precompute and stop caring about this:

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

以下是两种下划线方法的快速演示: http://jsfiddle.net/ambiguous/dNgEa/

Here's a quick demo of the two Underscore approaches: http://jsfiddle.net/ambiguous/dNgEa/

这篇关于Backbone.js将此绑定到$ .each的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆