Thursday, March 5, 2009

Function.createCallback

In my earlier post, I had given some details about the Function.createDelegate function. Actually there exists another function Function.createCallback with similar functionality. It doesn’t actually maintain the instance of the object. The only similarity is that it creates a wrapper function around the callback method provided.

The format of the function is:

Function.createCallback(callbackMethod, context)

So, what is the purpose of this function?  Let me demonstrate this with a simple example. Let us assume that we have a table with id “TestTable”. Clicking each row should bring up an alert box showing the row number clicked. The callback method used should be the same for all the rows.

Let us try:

var table = $get(‘TestTable’);
var rows = table.getElementsByTagName(‘tr’);

for(var i = 0; i < rows.length; i++) {
    $addHandler(rows[i], ‘click’, callbackMethod);
}

Now the problem. From within the callback method, how can we know which row was clicked. We need to show the row number clicked. This is where Function.createCallback kicks in. The context parameter given to this function would be passed on to the callback function when it is called by the $addHandler method. We could re-write the loop as:

for(var i = 0; i < rows.length; i++) {
    var callback = Function.createCallback(callbackMethod, { num:i });
    $addHandler(rows[i], ‘click’, callback);
}

Now the callback function can be implemented as:

function callbackMethod(e, context) {
    alert(‘Row Clicked: ‘ + (context[‘num’] + 1));
}

This should display the row number clicked.

Technorati Tags: ,

del.icio.us Tags: ,

No comments:

Post a Comment