Wednesday, August 15, 2012

Instrument javascript functions with before and after hooks

Use-Case:

I have a javascript class that i want to intrument in an aspect oriented programming (AOP) style by adding before and after hooks to every method in the class. I want to do this generically.

The before function should take the same arguments as the instrumented function and return a set of modified (or not) arguments for the instrumented function.

The after function should take the same arguments as the arguments passed to the instrumented function.

You can also do other things, for example the before function could abort the call to the instrumented function and the after function could munge the returned value.

Solution:

I decided to add the before and after functions as properties of the instrumented function. Remember, in javascript functions are also objects and can have properties added just like any javascript object.

Once my class's functions are instrumented the code that uses the class remains the same, but new code can now define the new before and after functions:
MyClass.someMethod.before = function(...) { ... }

Code:
Note: This code makes use of underscore.js

Final Thoughts:
The code as it stands now does not allow the programmer to define multiple before and after functions, only a single one can exist at one time. In the future I may consider supporting binding multiple functions.