documentcloud/underscore — pull request #541 by kevinrobinson (2012-04-05 19:02:10+00:00)
Title: Add optional context to _.tap

Nothing big. This just adds an optional context argument to _.tap() so that you can pass it that way instead of _.bind()ing the interceptor manually.

Before:

MyCoolObject.prototype.doSomething = function() {
return _.tap(this.calculateValueOfX(), _.bind(function(x) {
this.doSomethingElse(x);
}, this));
};

After:

MyCoolObject.prototype.doSomething = function() {
return _.tap(this.calculateValueOfX(), function(x) {
this.doSomethingElse(x);
}, this);
};

Also, if I run the example shown in the documentation, I get TypeError: Illegal invocation in Chrome. I assume this is from trying to call the interceptor (console.log) in the global context rather than in the context of console. This pull request fixes the documented use (which otherwise could be fixed by binding console.log to console).

_.chain([1,2,3,200])
.filter(function(num) { return num % 2 == 0; })
.tap(console.log, console)
.map(function(num) { return num * num })
.value();

Thanks!