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.

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

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

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.

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

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.

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.

Thats better, short and simple.

Leave a Reply

Close Menu