views:

937

answers:

2

I have an ASP.Net control that injects a javascript pageLoad function. I also have a pageLoad function directly on the page. I can't seem to get them both to fire. Are you limited to only a single function with the same name in javascript?

A: 

I have to disagree with Shog9...

I know it's possible to have multiple $(document).ready(f(n)) calls in a single document, with each being called in turn when the DOM finishes loading. I don't believe that multiple calls to ClientScript.RegisterStartupScript() cause any issues either.

Josh E
Josh, you're talking about jQuery, which supports binding multiple handlers to a single event. He's talking about the built-in ASP.NET AJAX auto-binding of the global pageLoad function. While ASP.NET AJAX also supports binding multiple handlers to a single event, that does not change the fact that the underlying language does not support multiple functions with the same name!
Shog9
ahh good point! I missed that in the original post. Thanks for correcting me on that
Josh E
+6  A: 

Yes... Like most languages, JavaScript requires symbols to be unique within their scope. In JavaScript, if you create multiple definitions for a function within a given scope, then the last one to be defined "wins" - it will be as though the previous definitions never existed.

What you need to do, in order to make your redundant pageLoad function work, is to use the Sys.Aplication.add_load() method. Using it, you can attach as many handlers as you want to the page load event. What's more, you can use anonymous function to add in the add_load method. Doing this will guarantee you that there is no danger of to handlers with duplicate names. Example:

StringBuilder sb = new StringBuilder();
  sb.Append("Sys.Application.add_load(");
  sb.Append("function() { alert('page load'); });");

ClientScript.RegisterStartupScript(this.GetType(), "Page_Load", sb.ToString(), true);

You can as easily use the Sys.Application.add_load on the client side, you can even add the same handler more than once. This will result in firing the same function multiple times :)

Genady Sergeev