An Original Idea

because all great software begins with an original idea

Archive for January 1st, 2012

Aspect Oriented Programming in Javascript

Posted by anoriginalidea on January 1, 2012

 

In designing javascript for modularity and “separation of concerns”, I was pleasantly surprised to discover a way of implementing AOP (Aspect Oriented Programming) in Javascript.

 

AOP can be useful for automatically “wrapping” methods to provide tracing, error logging or caching.

In this example, we are “wrapping” a method to show an alert when a method starts and finishes:

$.aop.around({ target: homelinksModel, method: 'get' }
 , function (invocation) {
alert("Method Call");

var ret = return invocation.proceed(); // This line calls the original method
alert("After Call");
return ret;
});

I used it for caching using Lawnchair  (an abstraction around local storage on client browsers).  It is designed to cache the result of data calls to the server.

$.aop.around({ target: homelinksModel, method: 'get' }
 , function (invocation) {
var lc = new Lawnchair(function () { });
var keyName = 'homelinksModel' + invocation.method;
var rec;
lc.get(keyName, function (ret) {
if (ret == null) {
    res = invocation.proceed()
    lc.save({ key: keyName, value: res });
    rec = res;
 }
 else {
 rec = ret.value;
 }
});
return rec;
}); // </aop>

I’m still learning Lawnchair, so there’s probably better ways of implementing this, but I thought a “useful” example might be helpful.

Peter Chung has an excellent article about Jquery AOP if you’d like to learn more.

There’s not alot of recent “action” around AOP in the Javascript space (Google Search).   I suspect that either some of it’s functionality is automatically part of jQuery or that the Javascript world isn’t mature enough yet to care much.    Perhaps it’s the former.

Over the past few days I’ve had a marvelous time implementing the MVVM pattern in Javascript.  I’m discovering all my favourite technologies are there, such as object databases (Lawnchair), binding (Knockout) and much more.  I hope to be blogging more about some of these soon.

Links

 

 

Posted in Uncategorized | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 108 other followers