3

Problem: I have a user control (.ascx) with a ton of javascript code in there. I have two instances of the user control on the same page. When the code runs the two user controls behave erratically because all the js objects with the same name can only have one value (including functions). The javascript is in the code behind and it is registered via "ScriptManager.RegisterStartupScript(.....)".

I've searched thoroughly and although there are a few threads with suggestions I found nothing that works other than literally going through the whole user control and appending an ID to function names that raise collision problems. (which requires meticulously going through all the code and deterimining if it is problematic).

example:

Dim asdf As String = ""
asdf &= "function foo" & UNIQUE_ID & "() {" & vbCrLf
asdf &= .....u get the idea......
asdf &= "}"

Is there a more elegant solution than this? Is it just bad practice to put javascript inside user controls for this reason?

1 Answers1

1

Maybe try to close all the JS code of a single control in a namespace? So the resulting code could look something like this:

var controlNamespace = {
   ...here goes the code that you have now for a control
};

You'll be able to call your functions by adding "controlNamespace." prefix. The only thing you need to care about then is that each control's script is enclosed in different namespace. Which should be pretty easy, assuming that you crete all the JS code dynamically on the server side, like in the example you pasted. This way every control will have it's corresponding code enclosed in a separate namespace and they won't interfere with themselves no matter how many of these controls you create on a page.

Rocky Balboa
  • 1,456
  • 2
  • 13
  • 21
  • I'd add to this, that the OP should have a good read of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures. – Adrian Wragg Sep 19 '13 at 22:27
  • The challenge with this solution is that I would need to add to the namespaces dynamically since there are many ScriptManager.RegisterStartupScript calls. Or possibly just have a different namespace for each call but that would mean I'd have to update each of the functions references that aren't in the same namespace. My plan now is to just refactor the user control so that I only need to instantiate it once – Jacob Moisan Sep 20 '13 at 15:00