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