How do you handle JavaScript binding to UserControls in ASP.NET and isolate multiple instances?

Suppose you need to attach some JavaScript functionality to an ASP.NET custom element that can have multiple instances on any given page. Since JavaScript has a common global state, what methods can you use to persist the state and client behavior for each control instance separately?

0


source to share


3 answers


Well, the main thing you can do is make sure that your JavaScript functions are abstract enough that they are not tied to concrete instances of HTML controls - have them take parameters that allow you to pass different object instances.

The JavaScript that does all it needs to be done should only exist once on your page, no matter how many instances of the custom control you have on a given page, so your functions should be unaware of this fact.

Without further information on what you are trying to do, there is a little more that I can offer in the form of help; it will depend on your circumstances.




EDIT: One way I've come across specific aspects of this issue is to create a static property in the custom control (thus it's the same variable across multiple instances) that keeps track of the client-side IDs of various custom controls ( the custom control adds client IDs to this list in the control's OnLoad event); then, in the OnPreRender (IIRC) event page , output them in a JavaScript variable that my code knows to look up on the client and work. I don't know if this makes sense, but it might help someone ...

+2


source


function <%=this.ClientID %>_myButton_onclick()
{
    DoSomething();
}

      

and



<button id="myButton" onclick="<%=this.ClientID %>_myButton_onclick()">

      

Note that in this case, the control is a regular HTML control.

0


source


If your control has more than one function, you can put it in external js files and reference it.

 this.Page.ClientScript.RegisterClientScriptInclude("searchcontrol.js","includes/searchcontrol.js");

      

0


source







All Articles