Reputation: 18318
I don't understand the purpose of a context variable for many of the underscore.js functions. What purpose does it serve. I know that it binds "this" in the iterator callback, but I don't understand the practical application of it.
var context = {'a': 'a'};
_.each([1, 2, 3], function(element, index, list)
{
console.log(this);
console.log(element);
console.log(index);
console.log(list);
}, context);
Upvotes: 3
Views: 1394
Reputation: 85
As of version there are about 21 functions in underscore that accept 'context' as last optional argument.
_.each(list, iteratee(element, index, list), [context])
Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed.
var array_1 = ['asdf', 'ghjk', 'lzxc', 'vbnm', 'qwer', 'tyui', 'op'];
var array_2 = [1,0,2,9,3,8,4,7,5,6];
_.each(array_1, function(element, index, list){
console.log(this.length - index + " - " + this[this.length - index]);
}, array_2);
will output
1 - asdf
0 - ghjk
2 - lzxc
9 - vbnm
3 - qwer
8 - tyui
4 - op
here this is corresponds to the context array array_2.
Upvotes: 0
Reputation: 1420
It's realy helpfull when you dont need a context change, don't forget about it's hard dependecy brother Backbone.
var Collection = Backbone.Collection.extend({
//..
_toggleActive: function (model, state) {
model.set({
active: state
});
},
deactivateAll: function () {
// analog _.each(this.models , func, [context])
this.each(function (model) {
// call the method of collection from context
this._toggleActive(model, false);
}, this);
}
//..
});
Or just for debug
_.each([1,2,3], function(item, i, arr){
this.log(item, i);
}, console);
Upvotes: 0
Reputation: 569
It's useful if your iterator function is something like a method on an object:
var context = {'a': 'a', foo: function(x) { console.log( this.a + x); }};
_.each([1, 2, 3], context.foo, context);
Upvotes: 2
Reputation: 17434
Underscore's _.each
looks like this:
_.each(list, iterator, [context])
Contexts are very useful when your iterator is a member of some object you've created, and you want to execute that function in the scope of the object and not of the window. If your pre-written function that you're using as an iterator uses this
to refer to an instance of an Object (as is generally the case), calling the function without context will result in this
referring to the wrong thing.
Upvotes: 2