Search code examples
javascriptasp.netuser-interfacetelligent

Multiple Controls on a Page with Multiple Instances of Javascript


I have created a Web Control in ASP for use in integrating with Telligent CommunityServer. The control is written in ASP with some 10 lines of C# backend for controlling visibility of the UI elements based on permissions, but I'd say 90% of the functionality is straight-up Javascript.

The control works beautifully, until you drop two instances of the Control on the same page--since they reference the exact same Javascript functions, only one control works.

How can I take this functionality that I have, this 1200 lines of Javascript, and make it so that each instance of the control can reference its each unique instance of Javascript?


Solution

  • If the problem is simply finding out which HTML element triggered an event then that's easy - it's passed to you in the event arguments. (You can then get its parent element, of course.) So if I understand the problem correctly you have JavaScript functions referencing some controls, which get duplicated?

    I don't think there's any magic solution here: you just have to make the IDs unique. If you're not using server-side controls (which handle this for you automatically) then you could use some server-side generated prefix or suffix, eg.

    <input id="<%= ParentControlId %>_mytextbox" type="text" />
    

    where ParentControlId is a unique ID of the parent control (you could just use Control.ID if you don't mind long IDs).

    Of course, you should try to re-use your JavaScript functions rather than duplicating them for each control instance. If you're using the server-generated ID approach you'll have to pass entire IDs around. If you're using the prefix approach you can just pass around the prefix.