Skip to content Skip to sidebar Skip to footer

Backbone.js Bind This To $.each

I'm using backbonejs and inside a method I have: $.each(response.error, function(index, item) { this.$el.find('.error').show(); }); However, because it's in $.each, this.$el i

Solution 1:

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

each_.each(list, 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.

So you could do this:

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

Or you could use _.bind:

$.each(response.error, _.bind(function(index, item) {
    this.$el.find('.error').show();
}, 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();
});

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

Solution 2:

Set a local variable before looping:

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

Post a Comment for "Backbone.js Bind This To $.each"