One of my current projects requires a Web form with AJAX interaction between a TextBox and a ListBox. As a user types into the TextBox, the keyup of event triggers and async postback to filter the list of items in the listbox. I used the Sys.Application.add_load accessor and $addHandler method to accomplish this as follows:
Sys.Application.add_load(PageLoad);
Sys.Application.add_unload(PageUnload);
function PageLoad(sender, args)
{
var txtbox = $get('<%= SearchBox.ClientID %>');
$addHandler(txtbox, "keyup", fn_KeyPress);
}
function PageUnload(sender, args)
{
var txtbox = $get('<%= SearchBox.ClientID %>');
$removeHandler(txtbox, "keyup", fn_KeyPress);
}
The problem is that, on each postback, the handlers are added again. So, on the first keyup event, the handler method is fired once. On the second keyup event, the handler method is fired twice, and so on. This is a problem.
The solution to determine, through JavaScript, whether the page is a postback of not. This can be accomplished by the Sys.ApplicationLoadEventArgs.isPartialLoad property. I added it int the Load handler method as follows:
function PageLoad(sender, args)
{
if (!args.get_isPartialLoad())
{
var txtbox = $get('<%= SearchBox.ClientID %>');
$addHandler(txtbox, "keyup", fn_KeyPress);
}
}
Problem solved!