Sunday, 3 February 2008

"Overriding" a third-party method in javascript

One of my colleagues recently had an issue with a javascript validation method that was being generated (and called) by trinidad. He wanted to change the behavior of the method (basically adding a guard clause in the beginning), and did this by copy pasting the existing method, modifying and defining it again. He knew this was asking for trouble anytime the trinidad implementation changes, so I helped him work out a better solution.

Since in javascript, functions are full-fledged objects, you can have references to them (this is something that escapes most programmers when they only have a basic knowledge of javascript). But in our case, that provides everything we needed to solve our problem. So I suggested something like this instead:

//keep a reference to the original function
//notice we don't use (), otherwise we'd execute the function.
var origThirdPartyFunction = nameOfTrinidadFunction;
//make the name of the original function point to our version
nameOfTrinidadFunction = patched;
	
//our version of the fuction
function patched() {
	//check some stuff before
	if(someCondition) {
		return;
	}
	//call original trinidad method
	origThirdPartyFunction(arguments);
}

The trick is in the first line: you can refer to a function by assigning it to another var if you don't actually call it by using round brackets. In the next line, we're doing the same, but now with the function we defined ourselves. In that function, we call the original function with the name we gave it.

So now, anytime trinidad calls the function under its original name, our version will get executed instead. This way, we could add the guard clause, without potential breakage should the trinidad implementatin change, since we no longer copy it's implementation.

Now, there are also other ways to implement this, like using AOP with javascript :)

Technorati Tags:

Posted by cvf at 5:15 PM in Java

« February »
SunMonTueWedThuFriSat
     12
3456789
10111213141516
17181920212223
242526272829