_.Each context variable
I don't understand the purpose of the context variable for many underscore.js functions. What purpose does it serve. I know it binds "this" in the iterator callback, but I don't understand its practical use.
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);
source to share
The underline _.each
looks like this:
_.each(list, iterator, [context])
Contexts are very useful when your iterator is a member of some object that you created and you want to execute this function on the object's scope, not the window. If your pre-written function that you are using as an iterator uses this
to reference an instance of an object (as is usually the case), calling the function without context will result in this
referring to the wrong thing.
source to share
This is very useful when you do not need to change the context, do not forget it hard.
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 debugging
_.each([1,2,3], function(item, i, arr){
this.log(item, i);
}, console);
source to share
The version has about 21 underscore functions that take "context" as the last optional argument.
_. each (list, iteratee (element, index, list), [context])
Iterations over a list of items, each of which results in an iteration function. The iterator is bound to the context object, if 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);
deduces
1 - asdf
0 - ghjk
2 - lzxc
9 - vbnm
3 - qwer
8 - tyui
4 - op
here it corresponds to the context array array_2.
source to share