views:

53

answers:

1

Hello,

In my current project, I am creating a number of user controls, some of which include some custom Javascript for event handling on the client side. I am registering my event handlers using OnClientClick="function()" and the like.

Now, I'm wondering how to ensure that all Javascript function names are unique for each specific instance of the control, so I don't risk name conflicts between controls. I have thought about putting all functions inside a named object, like

var <%=ClientID%>_Script {
  method1: function() { ...}
}

and then subscribing to events using something like

OnClientClick="<%=ClientID%>_Script.methodName()"

It just seems like I can't but <%= %>-expressions inside OnClient* attributes. I am therefore wondering; are there some "best practices" for doing this?

+1  A: 

The quickest solution might be to simply have a generic event handler which delegates to the appropriate handler:

OnClientClick="handleClick(this)"

this in the scope of the onclick attribute is the current element being clicked.

The ASP.NET way would be to register the client script. Specifically, see their recommendations under Referencing Controls Rendered Inside Other Controls (create script dynamically and register it.)

Blixt