Tuesday 11 December 2012

CoffeeScript aspects

Hojoo! First "real" blog message coming, finally!

There are some cases when client implementation shoudn't be available for everyone. I encountered such a problem when I was creating Backbone views for different users: users may have different roles, and depending on those roles, some actions should be available or not.

Of course I could have just ignored the actions is my Javascript. In this case, the whole implementation had to be hidden so if-else was out of question. Making different views for different role combinations is just plain stupid.

I decided to solve the problem by using using aspect oriented programming. Javascript functions have apply-method so it was quite trivial to make a simple aspect library:


Usage is trivial: just call @around-method and give the function name (pointcut) which must be wrapped. When function is called, the wrapper code is called first. It can decide whether to execute the original code via joinpoint interface or not. It can also modify function call argumens and return value. Joinpoint supports following functions:

Now I just have to make a basic Backbone view which is public for everyone. When I fetch the roles during page render, I can include all needed logic in separate files. Those files add the logic by binding their advices to the basic view. I can also apply some security policy for those Javascript "extensions", completely hiding the "secret features" from unwanted users. Pretty handy, I think! :)