Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- A = function(){
- alert("I'm a naive function");
- };
- B = function(){
- alert("I'm having a piggyback ride on function A!"+
- "And the fool doesn't even know it!");
- };
- addHook(B, A)//add hook B to function A
- A()
- //getting alerts "I'm a naive function"/"I'm having a
- //piggyback ride on function A! And the fool doesn't even know it!"
- <script>
- function A(x) { alert(x); return x; }
- function B() { alert(123); }
- function addHook(functionB, functionA, parent)
- {
- if (typeof parent == 'undefined')
- parent = window;
- for (var i in parent)
- {
- if (parent[i] === functionA)
- {
- parent[i] = function()
- {
- functionB();
- return functionA.apply(this, arguments)
- }
- break;
- }
- }
- }
- addHook(B, A);
- A(2);
- </script>
- function someFunction() { alert("Bar!") }
- var placeholder=someFunction;
- someFunction=function() {
- alert("Foo?");
- placeholder();
- }
- var function_itself = function() {
- alert('in function itself');
- }
- function_itself.PRE_PROCESS = function() {
- alert('in pre_process');
- }
- function_itself.POST_PROCESS = function() {
- alert('in post_process');
- }
- var function_processor = function(func) {
- if (func.PRE_PROCESS) {
- func.PRE_PROCESS.call();
- }
- func.call();
- if (func.POST_PROCESS) {
- func.POST_PROCESS.call();
- }
- }
- // usage:
- /*
- function test(x) {
- alert(x);
- }
- var htest = hookable(test);
- htest.addHook("before", function (x) {
- alert("Before " + x);
- })
- htest.addHook("after", function (x) {
- alert("After " + x);
- })
- htest("test") // => Before test ... test ... After test
- */
- function hookable(fn) {
- var ifn = fn,
- hooks = {
- before : [],
- after : []
- };
- function hookableFunction() {
- var args = [].slice.call(arguments, 0),
- i = 0,
- fn;
- for (i = 0; !!hooks.before[i]; i += 1) {
- fn = hooks.before[i];
- fn.apply(this, args);
- }
- ifn.apply(this, arguments);
- for (i = 0; !!hooks.after[i]; i++) {
- fn = hooks.after[i];
- fn.apply(this, args);
- }
- }
- hookableFunction.addHook = function (type, fn) {
- if (hooks[type] instanceof Array) {
- hooks[type].push(fn);
- } else {
- throw (function () {
- var e = new Error("Invalid hook type");
- e.expected = Object.keys(hooks);
- e.got = type;
- return e;
- }());
- }
- };
- return hookableFunction;
- }
Add Comment
Please, Sign In to add comment