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.