Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net AJAX multiple pageLoad functions possible?

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?

like image 464
Jared Avatar asked Jun 12 '09 18:06

Jared


1 Answers

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.Application.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 :)

like image 122
Genady Sergeev Avatar answered Oct 14 '22 04:10

Genady Sergeev