Javascript Anonymous Methods and How they help Ajax WebMethod

Ok so here’s what you’re trying to do:

You have a button and when it’s pressed you want to have it fill a drop down list without a postback. So your first thoughts are, “I like Mentos” followed by, “WebMethod” since you of course read this super awesome post. Now it might look like this:

        function GetUserList()
        {
            PageMethods.GetUserList(OnGetUserListComplete);
        }

        function OnGetUserListComplete(result)
        {
            var dropdownList = $get('dropdownListID');
            for (var i = 0; i < result.length; i++)
            {
                var item;
                item = document.createElement("option");
                item.text = result[i].UserName;
                item.value = result[i].UserID;
                dropdownList.options.add(item);
            }
        }

And GetUserList would be called on click. Fine and dandy, but this sort of bad since you’re hardcoding the id of the control. Meh. You look back at the method and see that there just isn’t a way to pass in a name, and if you didn’t you would be sooooo wrong it hurts. Shame on you. Good thing I’m here. The way you’re going to do this is to use an anonymous method. You see, as it is the PageMethod call needs a method to call post completion and that’s all it takes in. (Well not completely true, it can take in parameters for the server side method, but that’s not the point.) So you have to find a way for that PageMethod to call the method after completion AND make sure it has the list name with it.

        function GetUserList(dropdownList)
        {
            PageMethods.GetUserList(function(result) {
                 OnGetUserListComplete(result, dropdownList); });
        }

        function OnGetUserListComplete(result, dropdownList)
        {
            for (var i = 0; i < result.length; i++)
            {
                var item;
                item = document.createElement("option");
                item.text = result[i].UserName;
                item.value = result[i].UserID;
                dropdownList.options.add(item);
            }
        }

Ooo pretty tricky huh?

        PageMethods.GetUserList(function(result) {
                 OnGetUserListComplete(result, dropdownList); });

See what I did there, I created an anonymous method to be called on completion and in turn it calls the original (Though modified) OnGetUserListComplete method now. And you thought javascript sucked.