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 ?
-
It would help to know what you're trying to achieve.cletus– cletus2009年02月20日 07:16:16 +00:00Commented Feb 20, 2009 at 7:16
-
I haven't seen them myself, but I have a NIH tendancy...Simon Buchan– Simon Buchan2009年02月20日 07:28:40 +00:00Commented Feb 20, 2009 at 7:28
-
I still don't get the point: you want a library to save you 6 lines of code? Libraries are high cost in Javascript (whereas in C#/Java you seem to have them just cos you can). I can't say I've ever needed to write around advice in Javascript either.cletus– cletus2009年02月20日 07:35:15 +00:00Commented Feb 20, 2009 at 7:35
-
@cletus I probably write way larger javascript applications than most people, so even just a standardized pattern would have value. And javascript often surprises me by having some really clever solutions. Re-edited question.krosenvold– krosenvold2009年02月20日 07:57:35 +00:00Commented Feb 20, 2009 at 7:57
5 Answers 5
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.
Comments
The Dojo Toolkit has a lot of support for AOP constructs like this:
Eugene Lazutkin's Blog Post on Aspect Oriented Programming with Dojo
Comments
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 :
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
2 Comments
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.
Comments
There is now a Proxy built-in object in JavaScript