Lets say you need to attach some JavaScript functionality to an ASP.NET User Control of which there might be multiple instances on any given page. Because JavaScript has shared global state, what techniques can you use to keep the client state and behavior for each instance of a control separate?
views:
323answers:
2Well, the main thing you can do is make sure your JavaScript functions are abstract enough that they are not coupled to specific instances of HTML controls - have them accept parameters that allow you to pass various instances of objects in.
The JavaScript that does whatever magic you need to be done should only exist once in your page regardless of how many instances of a user control you have on a given page, thus your functions need to be ignorant of that fact.
Without more information about what you are trying to do, there is little more I can offer in the way of help; it would depend on your circumstance.
EDIT: One way I have dealt with particular aspects of this problem is to create a static property on the user control (thus it is the same variable across multiple instances) that tracks the client-side IDs of the various user control elements (the user control adds the client IDs to this list in the control's OnLoad event); then, in the page's OnPreRender event (IIRC), render those out in a JavaScript variable that my code knows to look for on the client and operate on. I don't know if that makes sense, but it might help someone...
function <%=this.ClientID %>_myButton_onclick()
{
DoSomething();
}
and
<button id="myButton" onclick="<%=this.ClientID %>_myButton_onclick()">
Notice in this case the control is a regular HTML control.