Search code examples
javascriptasp.netajaxweb-controls

WebControl creates JS object in a <script> tag, how to get the object in the page's JS?


I've been playing around with making my own WebControls, and am trying to add some AJAX functionality without using MS AJAX. I'm not sure of the best way to pass the JS objects from the WebControl's to the page's script.

I use Page.ClientScript.RegisterClientScriptResource to get my control's JS to the browser, and I instantiate the JS through the server code like so (RenderEndTag writes out a <script> that calls new):

public class SearchBox : WebControl
{
    //...
    public override void RenderEndTag(System.Web.UI.HtmlTextWriter writer)
    {
        //...
        writer.Write("<script type=\"text/javascript\">new SearchBox($('#" + this.ClientID + "'));</script>");
    }
}

Now I need to use the object in a specific page's JS (such as to add a valueChanged handler). How should I go about it? Would a global array with the control ID's as keys work?


Solution

  • Since you're using jQuery, one of the things you could do in your SearchBox's javascript constructor is something like this:

    var SearchBox = function($element) {
        $element.data("searchBox", this);
    }
    

    Then you could can easily retrieve this from jQuery again at a later point:

    var sb = $("#myElement").data("searchBox");