public
Last active

an advice functional mixin

  • Download Gist
advice.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
//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;
});
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.