Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  9] [ 3]  / answers: 1 / hits: 16540  / 15 Years ago, sat, april 25, 2009, 12:00:00

EDIT: OK, I believe the following solutions are valid:




  1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.

    If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.


  2. Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.

    You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.




I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.






Hi,



Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?



Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:



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!


I've been trying to hack something up for a couple of hours, but so far no luck.


More From » aop

 Answers
266

Take a look at jQuery's AOP plugin. In general, google javascript aspect oriented programming.


[#99647] Monday, April 20, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frederickmohamedw

Total Points: 21
Total Questions: 123
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
frederickmohamedw questions
Wed, Sep 23, 20, 00:00, 4 Years ago
Sat, Jul 18, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Sat, Jan 11, 20, 00:00, 4 Years ago
Fri, Dec 27, 19, 00:00, 4 Years ago
;