Creating extensible Prototype Widgets

Written by on December 6th, 2006 in Ajax News.

Justin Palmer has written about avoiding bloat in widgets with respect to Prototype.

Widgets walk a fine line between abstractions and implementations. Implementation, in this case, is a practical solution chosen to perform a given function. The problems with widgets occur when the widget author walks too far in one direction, or worse, walks an outward spiral covering both directions. Both choices lead to script bloat and complexity thats hard to manage. You no longer have a simple solution for a defined problem, you have a complex solution for a variety of problems. The good news is there are ways to avoid both the bloat and complexity.

He details the world of extending classes in JavaScript, and then gets to actsAsAspect, which lets you get AOP-y via before, after, and around advice.

function actsAsAspect(object) {
  object.yield = null;
  object.rv    = { };
  object.before  = function(method, f) {
    var original = eval(”this.” + method);
    this[method] = function() {
      f.apply(this, arguments);
      return original.apply(this, arguments);
    };
  };
  object.after   = function(method, f) {
    var original = eval(”this.” + method);
    this[method] = function() {
      this.rv[method] = original.apply(this, arguments);
      return f.apply(this, arguments);
    }
  };
  object.around  = function(method, f) {
    var original = eval(”this.” + method);
    this[method] = function() {
      this.yield = original;
      return f.apply(this, arguments);
    }
  };
}
 

As someone who has worked with AOP via AspectJ and other libraries, it makes me a bit queasy to consider this AOP. One of the key elements is the pointcut language, which is very primitive here.

I do like the conclusion though:

While this is a rather convoluted example, the premise is solid. When creating widgets, don’t over abstract, and avoid hacking when possible. Even though we jazzed up our widget in the end, it’s original purpose is still intact and we added no additional overhead to it. Those who want ”more cowbell” can get it by plugging-in the additional scripts.

Source: Ajaxian
Original Article: http://ajaxian.com/archives/creating-extensible-prototype-widgets

Leave a Reply

You must be logged in to post a comment.



Site Navigation