Tuesday, November 28, 2006

JavaScript actsAsAspect


The idea is that you run actsAsAspect() on any JavaScript object,
and then your object receives 3 extra methods:

  1. before()
  2. after()
  3. around()

You then can use those methods to setup the callbacks you need.


The Code:
function actsAsAspect(object) {
object.yield = null;
object.rv = { };
object.before = function(method, f)
{
var original = eval("this." + method);
this[method] = function()
{
this.rv[method] = f.apply(this, arguments);
if (this.rv[method] == false)
return false;
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);
}
};
}

Example: Applying actsAsAspect() to window


actsAsAspect(window);
function haha() { return "HA Ha ha ha..."; }
after('haha', function() { alert(this.rv['haha']); });
haha();


Full information can be found:

http://beppu.lbox.org/articles/2006/09/06/actsasaspect

No comments: