Welcome Guest
( Log In | Register )
The time is now 11:29 pm
You last visited January 19, 2022, 11:02 pm
All times shown are
Eastern Time (GMT-5:00)

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

Published:

Last Edited: January 14, 2008, 2:52 pm

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.  ;-)

Entry #14

Comments

This Blog entry currently has no comments.

You must be a Lottery Post member to post comments to a Blog.

Register for a FREE membership, or if you're already a member please Log In.