Agile Tortoise
Greg Pierce’s blog
« Servoy 4.0 goes final Testing WordPress for iPhone »
Servoy: wrapping global methods
One of the best things about Servoy 4 is the dramatically improved JavaScript support. With full support for functions, and the "apply", method you can now do very cool things in the runtime environment.
The example below shows how to take a pre-defined global method, alias it, and replace the original with a new version that is wrapped with 'before' and 'after' callbacks. This is very useful for development and testing purposes -- for example, you might write a version of this that wraps a method in some profiling code to track execution time. Then you don't have to bug down your original code with profiling code, but when necessary you can have an "enter profiling mode" method to call that uses this to alias a number of important methods you want to track in the runtime.
-
function wrap_global_method()
-
{
-
var orig = arguments[0];
-
var before = arguments[1] || null;
-
var after = arguments[2] || null;
-
var newName = orig + '_orig';
-
-
if(typeof globals[newName] == 'function')
-
globals[orig] = globals[newName];
-
globals[newName] = globals[orig];
-
-
var repl = function() {
-
switch(typeof before)
-
{
-
case 'string' : eval(before); break;
-
case 'function' : before(); break;
-
}
-
var result = globals[newName].apply(this, arguments);
-
switch(typeof after)
-
{
-
case 'string' : eval(after); break;
-
case 'function' : after(); break;
-
}
-
return result;
-
}
-
globals[orig] = repl;
-
}
In usage, you can pass either functions, or raw strings of code to make the 'before' and 'after' callbacks. To keep the example simple, it only supports one level of aliasing -- ie, if you call it twice you'll replace your original aliased version, rather than stacking them multiple levels deep. Example
-
globals.wrap_global_method('myGlobalMethod',
-
function() { application.output('before!'); },
-
function() { application.output('after!)'; }
-
);
After you do this, anytime 'globals.myGlobalMethod()' is called in your solution, the 'before' and 'after' callbacks will also be executed. Fun!