Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  101] [ 4]  / answers: 1 / hits: 16846  / 12 Years ago, wed, june 27, 2012, 12:00:00

I need to trigger function bar() whenever function foo() fires. I have no control over function foo or whether it will change in the future. I have this situation regularly (and I hate it).



I wrote this function to add my code to the end of function foo:



function appendToFunction(fn,code){ 
if(typeof fn == 'function'){
var fnCode = fn.toString() ;
fnCode = fnCode.replace(/}$/,code+n}) ;
window.eval(fnCode); // Global scope
return true ;
}
else{
return false ;
}
}


eg:



appendToFunction(foo,bar(););


This strikes me as a terrible idea - but it works. Can somebody point me in a better (safer) direction please.



EDIT: foo is not a specific function, but many functions that I wind up dealing with. They don't change dynamically in the page. But they may be changed (eg. form validation demands) from time to time.



Solution:
I settled on a modified version of Adam's Answer. It's not perfect, but it's better than what I had:



var oldFoo = foo ;
foo = function(){
var result = oldFoo.apply(this, arguments);
bar();
return result ;
}


NB. Watch out for some native functions in IE6/7 that don't have an .apply() method.


More From » eval

 Answers
75

You can just override foo with a custom function that calls the original.



E.g.



var old_foo = foo;
foo = function() {
old_foo();
bar();
}


You should also pass any arguments foo takes into it via your replacement function.


[#84635] Tuesday, June 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
braydon

Total Points: 0
Total Questions: 102
Total Answers: 111

Location: Sao Tome and Principe
Member since Wed, Dec 29, 2021
2 Years ago
;