Skip to content

Instantly share code, notes, and snippets.

@jurberg
Last active December 27, 2015 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jurberg/7303480 to your computer and use it in GitHub Desktop.
Save jurberg/7303480 to your computer and use it in GitHub Desktop.
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