Last active
August 29, 2015 14:16
-
-
Save gwendall/c9e292792b5bbb904da3 to your computer and use it in GitHub Desktop.
Hijack callback for any function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Takes any function with a callback as last parameter, and allow to add it another callback executed before it. Requires underscore. | |
Example: | |
Mongo.Collection.prototype.insert = extendWithCallback(Mongo.Collection.prototype.insert, function() { | |
console.log("This logs every time an insert is done on a collection, even though we did not explicitely declared a callback when calling insert"); | |
}); | |
var items = new Mongo.Collection("items"); | |
items.insert(selector, modifier); | |
*/ | |
Function.prototype.clone = function() { | |
var that = this; | |
var temp = function temporary() { return that.apply(this, arguments); }; | |
for (var key in this) { | |
if (this.hasOwnProperty(key)) { | |
temp[key] = this[key]; | |
} | |
} | |
return temp; | |
}; | |
var extendCallback = function(fn, cb) { | |
if (!_.isFunction(fn) || !_.isFunction(cb)) return; | |
fn = fn.clone(); | |
return function() { | |
var fnContext = this; | |
var fnArgs = _.toArray(arguments); | |
var fnCallback = _.last(fnArgs); | |
var hasCallback = _.isFunction(fnCallback); | |
if (!hasCallback) return; | |
fnArgs.pop(); | |
fnArgs.push(function() { | |
var cbContext = this; | |
var cbArgs = _.toArray(arguments); | |
cb.apply(cbContext, cbArgs); | |
fnCallback.apply(cbContext, cbArgs); | |
}); | |
fn.apply(fnContext, fnArgs); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment