Monday, January 14, 2008

ASP.NET AJAX: Half-way between createDelegate() and createCallback()

I stumbled on a use of Function.createDelegate() method today that seems to be a cross between Function.createDelegate() and Function.createCallback().

I had the need to pass a context to a handler function, with the context being a JSON object containing the state of a few variables.  I tried using createCallback(), which is designed for that purpose, but it did not seem to work well because I was not using it together with a DOM event — just with an internal function call.

So I turned to createDelegate(), using the JSON object as the this argument, and it worked quite nicely.

An example of this syntax is as follows.  The code assigns a function to the variable fn that (when called) displays an alert box containing the element number and id of a DIV with an ID of "ThisOne".  There are certainly more useful uses for this method, but it should provide a clear example of how it works.  The key point here is the function() assignment that uses this to utilize the values passed in the delegate.

var a = document.getElementsByTagName("div");
var fn;

for (var x=0; x < a.length; x++) {
    if (a[x].id == "ThisOne") {
        fn = Function.createDelegate({
            e: a[x],
            num: x
        }, function () {
            alert("DIV #"+this.num+": "+this.e.id);
        });
    }
}

fn();

If you're not sure about the value of the above code, ask yourself, "How would I code the same thing without the createDelegate()?"  Also ask yourself how hard it would be to pass the DOM element itself to your function, as I have done with createDelegate().

Would you use the Function() constructor that allows you to create a dynamic function from a string value?  (Bad idea.)

Would you use global variables?  (Bad idea.)

If your answer is that you'd use apply(), then you're doing the same thing that createDelegate() does internally.  If you didn't think of that before you read this, then you can't claim credit for thinking of it.  ;-)

0 Comments:

Post a Comment

<< Home