Wednesday, March 4, 2009


In order to manipulate callback event of DOM objects, Asp.Net Ajax comes with a handy set of functions. One of such handy method is the $addHandler method. Usage is straight forward. The syntax is:

$addHandler(domObject, eventName, callbackFunction);

Everything works perfectly. The only problem is when you use the function with the callback method as a method within an object, 

For example, we have a class:

var TestClass = function() {
   this.testVar = “Test Variable”;

TestClass.prototype = {
   testFunction: function() {

Now, if we have a DOM element with ID ‘TestElement’, we could register the click event of the element using:

$addHandler($get(‘TestElement’), ‘click’, this.testFunction);

When clicked, the element will show a dialog box ‘Undefined’. This is because, when an element is ‘clicked’, within the callback method, this refers to the instance of the event object. Since the event object instance does not have a variable called testVar, we get an ‘undefined’ prompt.

To overcome this limitation, we have the Function.createDelegate method. The format of this method is:

Function.createDeleagte(instance, event, callbackMethod);

This essential creates a wrapper function around the callback-method. When the wrapper function is called by the event handler, it delegates the call to the callbackMethod in the proper manner so that the this keyword will refer to object instance, which was provided as the first parameter to the createDelegate method. An example usage would be:

var del = Function.createDelegate(this, this.testFunction);
$addHandler($get(‘TestElement’), ‘click’, del);

Technorati Tags: , Tags: ,

No comments:

Post a Comment