Created
September 24, 2015 14:34
-
-
Save anonymous/5b2002a4335ce444e016 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ## $.withAdvice | |
// | |
// Borrowed by [Flight](https://github.com/flightjs/flight). | |
// | |
// `withAdvice` is a mixin that defines `before`, `after` and `around` methods. | |
// | |
// These can be used to modify existing functions by adding custom code. All | |
// components have advice mixed in to their prototype so that mixins can augment | |
// existing functions without requiring knowledge of the original | |
// implementation. | |
// | |
// Mixins will typically use the after method to define custom behavior for the | |
// target component. | |
// | |
// ### Example | |
// | |
// var foo = { | |
// print: function () { | |
// console.log("Hello"); | |
// } | |
// } | |
// $.withAdvice.call(foo); | |
// foo.after("print", function () { | |
// console.log("world"); | |
// }); | |
// | |
// foo.print(); //logs Hello world | |
// | |
(function ($) { | |
"use strict"; | |
$.withAdvice = function () { | |
var advice = { | |
around: function (base, wrapped) { | |
return function composedAround() { | |
var i = 0, l = arguments.length, args = new Array(l + 1); | |
args[0] = base.bind(this); | |
for (; i < l; i += 1) { | |
args[i + 1] = arguments[i]; | |
} | |
return wrapped.apply(this, args); | |
}; | |
}, | |
before: function (base, before) { | |
return function composedBefore() { | |
before.apply(this, arguments); | |
return base.apply(this, arguments); | |
}; | |
}, | |
after: function (base, after) { | |
return function composedAfter() { | |
var res = base.apply(this, arguments); | |
after.apply(this, arguments); | |
return res; | |
}; | |
} | |
}; | |
function unlockProperty(obj, op) { | |
op.call(obj); | |
} | |
["before", "after", "around"].forEach(function (m) { | |
this[m] = function (method, fn) { | |
unlockProperty(this, function () { | |
if (typeof this[method] === "function") { | |
this[method] = advice[m](this[method], fn); | |
} else { | |
this[method] = fn; | |
} | |
return this[method]; | |
}); | |
}; | |
}, this); | |
return advice; | |
}; | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment