views:

280

answers:

1

I am creating a custom .NET AJAX Server Control, and need to get access to the JavaScript object functionality associated with that control. I can do this by finding the control in the ScriptManager using the $find method. However, I need to determine when I can call $find. If I do this on the "onload" event of the body of my HTML page, it can't find the control. Thus I end up having to locate the control with each event I wire up and my code ends up looking like this:

function button1_click() {
    var control = $find("<%=Control.ClientID%>");
    control.DoSomething();
}

function button2_click() {
    var control = $find("<%=Control.ClientID%>");
    control.DoSomethingElse();
}

I would rather store that control once, and use it throughout the rest of my event calls. Thus I'm hoping the code would eventually look something like this:

var _control = null;
function load() {
     _control = $find("<%=Control.ClientID%>");
}

function button1_click() {    
    _control.DoSomething();
}

function button2_click() {
    _control.DoSomethingElse();
}

Let me know if this doesn't make sense. I am new at creating these custom controls, so I'm not quite sure of the terminology yet. Thanks for your help!

+1  A: 

The "load" DOM event occurs before the ASP.NET Ajax client-side framework is initialized. Client-side controls are initialized by handling the init event of the Sys.Application object. That's why an ASP.NET Ajax control's initialization script is output like:

Sys.Application.add_init(function() {
    $create( ... )
});

You can use the load event of the Sys.Application object or its shortcut- the pageLoad method. It occurs after the init event and all ASP.NET Ajax controls will be initialized then. Here is some sample code:

var _control = null;

function pageLoad() {
    _control = $find("<%= Control1.ClientID %>");
}
korchev
This was exactly what I needed. Thank you very much for your help!
Blake Blackwell