The ASP.NET AJAX client framework contains helpful shortcut
methods. Some of the methods are the $addHandler, $removeHandler,
$clearHandlers, $get, and $find. Each one of these performs some action.
$addHandler
The add handler method registers an event handler for a DOM
element's event. For instance, a button is either a hyperlink "a"
tag, or an "input" tag with a type of "button." The
$addHandler registers an event handler for that DOM event, such as the
JavaScript click event that fires when you click it. To create a delegate and
attach to the event, use the following approach:
Listing 5
var clickHandler = Function.createDelegate(this, this.clickCallback);
$addHandler(button, "click", this.clickHandler);
In the above method, clickCallback is the name of a method;
now _clickHandler contains a reference to the clickCallback method. In the
second line, get_element() returns a reference to a DOM element. The second
parameter defines the method to attach to (leaving out the "on"
prefix), and the third parameter specifies the delegate to use so that when the
DOM element is clicked, the delegate method is called, which points to
clickCallback. Now the _clickHandler is linked to clickCallback method, which
fires when the click occurs.
$addHandlers
This method is a helper method to register event handlers in
bulk. By providing a key/value pairing of event name/handler, this registers
for many events at once.
Listing 6
//textbox is DOM element
$addHandlers(textbox, {"keyup":keyupHandler, "keydown":keydownHandler});
$clearHandlers
This method clears all of the handlers that have been
established for a DOM element. It's a quick way to get rid of registered
handlers quickly:
Listing 7
//textbox is DOM element
$clearHandlers(textbox);
$removeHandler
This method removes a specific handler for a DOM element.
It allows you to specify the event and delegate to remove.
Listing 8
//textbox is DOM element
$removeHandler(textbox, "click", clickHandler);
$get
The get method is a shortcut for document.getElementById.
It allows you to reference a Dom element through its ID. What you have to
remember is that when the page runs, this often cannot be referenced by a
server control's ID directly, but its client ID. The approach you often see is
to embed the client ID through the following approach:
Listing 9
var textbox = $get("txt1");
$find
When a class is registered through the registerClass method,
this creates a hierarchy that sits between the DOM element and any server-side
components being registered as well (though classes don't all have server-side
components, features like AJAX controls and control extenders often do). This
method returns a reference to the class JavaScript component.
Listing 10
Var element = $find('<%= MyControl.ClientID %>');
element.set_Text("Some Value");
This allows you to access the class object and use the
helpful methods like get_Text and set_Text (as described next).