Skip to content

Instantly share code, notes, and snippets.

@angus-c
Created June 3, 2012 20:12
Show Gist options
  • Save angus-c/2864853 to your computer and use it in GitHub Desktop.
Save angus-c/2864853 to your computer and use it in GitHub Desktop.
an advice functional mixin
//usage
withAdvice.call(targetObject);
//mixin augments target object with around, before and after methods
//method is the base method, advice is the augmenting function
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 = util.toArray(arguments);
return wrapped.apply(this, [base.bind(this)].concat(args));
}
},
before: function(base, before) {
return fn.around(base, function() {
var args = util.toArray(arguments),
orig = args.shift();
before.apply(this, args);
return (orig).apply(this, args);
});
},
after: function(base, after) {
return fn.around(base, function() {
var args = util.toArray(arguments),
orig = args.shift(),
res = orig.apply(this, args);
after.apply(this, args);
return res;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment