Simple AOP in JavaScript

During a recent re-factoring of some JavaScript I accidentally removed the last line of a function that told the UI to re-render according to the new data. After that I figured, why not move this outside of the function and get a little AOP look and feel.

The code below gives a simplified version of the problem.

https://gist.github.com/3022884#file_initialcode.js

So with that in mind I created the three obvious methods, before, after and around.

https://gist.github.com/3022884#file_aspects.js

Sweet, now I can move that pesky line of code out of my implementation.

https://gist.github.com/3022884#file_refactoredcode.js

Apart from this very simple use case you could also use these functions to build chains, add logging, catch exceptions, filter calls depending on input or modify the entire function without touching the implementation. The next example is an example is to show how to build a throttle function using the around function. This use case is based on knockoutjs where you have the throttle functionality  for computed values. But what do you do when you really wants to use subscribe(since you have no reason to compute anything) and still needs to throttle the number of calls?

Lets take a peek on the code that works with knockouts built in compute functionality.

https://gist.github.com/3022884#file_initialthrottle.js

Then we got the code for the new throttle function using around.

https://gist.github.com/3022884#file_throttlefunc.js

Ok, looking at it now the use of around feels a bit pointless since we extend the Function object. So the alternative solution without around.

https://gist.github.com/3022884#file_throttlefunc2.js

So when do you need the around you might ask. Well, a lot of around functionality is not this generic and might not be suited to extend the Function object. That is when you slap on the around.

Anyways, lets get back to the knockout example and what the code looked like after the much needed refactor.

https://gist.github.com/3022884#file_throttlerefactored.js

Thats better, short and simple.

Leave a Reply

Close Menu