In an ASPX page or an ASCX user control, we can name our JavaScript functions using a prefix, <%=ClientID%>, in order to mitigate function naming collisions. In some applications, there can be a number of JavaScript functions, and in situations where we are continually adding more functions, sometimes we run the risk of repeating their names.
Perhaps I am the last person to realize, but to make my function names unique to my control or page, I can prefix them with <%=ClientID%>, as seen below.
Within an ASPX page:function <%=ClientID%>_TestMe(){ // do whatever}
Witin an ASCX user control:function <%=ClientID%>_TestMe(){ // do whatever}
When I include the above ASCX control within my ASPX page, essentially having two functions with the same name at design time, they are both rendered to the page's source with different names, as seen below.
<html> <head> <script> function <%=ClientID%>_TestMe() { // do whatever } </script> </head> <body> <form id="form1" runat="server"> <div> <uc:Grid id="gridView" runat="server"></uc:Grid> </div> </form> </body></html>
Page Source as it is Rendered:function __Page_TestMe(){ // do whatever}
function gridView_TestMe(){ // do whatever}
In my user control or page, I can reference my function with something like this.<input type="button" value="GO" onclick="<%=ClientID%>_TestMe()" />
Which gets rendered as this.<input type="button" value="GO" onclick="gridView_TestMe();" />
This will help reduce naming collisions when referencing JavaScript libraries, but it will not eliminate all of them.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2009 MuellerDesigns.net
Sign In