tags:

views:

188

answers:

4

I can proxy a single function in javascript by doing something like this (just jotted down from memory so bear with me)

function addAroundAdvice(target){
    var targetFunction = target.aFunction;
    target.aFunction = new function(){
           invokePreCall();
           targetFunction.apply(target, arguments);
           invokePostCall();
    }
}

Being a java programmer I'd think of this as a dynamic proxy. Every time I write code like this I think that someone must have made a really smart library that does the common proxying operations that is at least 10% better than what I can do in a hurry. I'd be expecting some stuff like correctly intercepting all methods for any given object, which may not be entirely trivial. Then there's different types of advice. So while I'm not expecting something the size of scriptaculous, it's certainly more than 6 lines of code.

So where are these libraries ?

A: 

The fact that you have been able to do it I would think means that there is a library to achieve it in the form of pure JavaScript i.e. your above example. Design Patterns can be applied to JavaScript as you know, so I think the advice I would provide to you is the following by a Google and Yahoo GUI developer :

http://jsdesignpatterns.com/

Chapter 14: The Proxy Pattern. Reference there solution to yours. You may still prefer your approach or you may find tips from their approach.

Cheers,

Andrew

REA_ANDREW
Thanks, I put the book in my amazon shopping basket. I know how to do most of these things, but I am fed up of constantly re-inventing this wheel.
krosenvold
Lol, good point! :-)
REA_ANDREW
+2  A: 

Try jQuery AOP plugin

Looking at the source it seems that only uses jQuery as a namespace, so you could try this plugin even if don't want to use jQuery.

Serhii
Oooo. Looks promising.
krosenvold
A: 

I don't think you can intercept all functions.

The best you can do is iterate over all elements of an object and look for any functions:

for elem in someObject {
    if typeof(elem) == "function" {
        // replace the function
    }
}

Trouble is, that if you add a function later it's not routed through the proxy.

Georg
A: 

The Dojo Toolkit has a lot of support for AOP constructs like this: [http://lazutkin.com/blog/2008/may/18/aop-aspect-javascript-dojo/][1]

[1]: http://lazutkin.com/blog/2008/may/18/aop-aspect-javascript-dojo/"Eugene Lazutkin's Blog Post on Aspect Oriented Programming with Dojo"

Gavin