Skip to content

Instantly share code, notes, and snippets.

@jurberg jurberg/advice.js
Last active Dec 27, 2015

Embed
What would you like to do?
sample advice extension. forgot the origins of this...
(function (exports) {
//usage
//withAdvice.call(targetObject);
//mixin augments target object with around, before and after methods
//method is the base method, advice is the augmenting function
exports.withAdvice = function() {
['before', 'after', 'around'].forEach(function(m) {
this[m] = function(method, advice) {
if (typeof this[method] == 'function') {
return this[method] = fn[m](this[method], advice);
} else {
return this[method] = advice;
}
};
}, this);
};
//fn is a supporting object that implements around, before and after
var fn = {
around: function(base, wrapped) {
return function() {
var args = Array.prototype.slice.call(arguments, 0);
return wrapped.apply(this, [base.bind(this)].concat(args));
}
},
before: function(base, before) {
return fn.around(base, function() {
var args = Array.prototype.slice.call(arguments, 0),
orig = args.shift();
before.apply(this, args);
return (orig).apply(this, args);
});
},
after: function(base, after) {
return fn.around(base, function() {
var args = Array.prototype.slice.call(arguments, 0),
orig = args.shift(),
res = orig.apply(this, args);
after.apply(this, args);
return res;
});
}
};
}(typeof exports === 'undefined' ? this.advice = {} : exports));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.