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
Hmm, this concerns me as well, you mentioned that
I have this situation regularly (and I hate it).
Do you mind if I ask in what scenario this keeps occurring? Is it in a corporate scale, or on a personal project scope? You've clearly got a level head on your shoulders and know that what you're doing is out of the ordinary, so I'm wondering if there is an alternatively solution.
The reason I ask is; this approach could potentially open a can of problems. What if foo
fails for example, or if foo
returns a value mid evaluation? By simply appending bar
to the actual function doesn't guarantee it will execute. Pre-pending it on the other hand means it's more likely to be executed, but still in my opinion isn't a good approach.
Have you considered revising the function foo
? I know this might seem like a silly question, but it might be worth it if you're encountering similar problems throughout. If you want to keep things abstracted you could adopt an "event handler" approach, whereby foo
triggers an event on the window
, which in turn then triggers bar
, would this work in your case.
Alternatively, if you know what foo
is, and what it does, you could hook into it's prototype if it's an object, and then amend the code there appropriately. You did however mention that this function is open to change, which may make this option redundant, but it's a possible solution nonetheless.