views:

41

answers:

2

In ASP.Net I have a few custom controls I've made. I utilized jQuery where it helped also. Well, one problem I have now(with obvious, but "bad" workarounds) is that for each user control I need to execute some code from within pageLoad($(document).ready will not work with update panels).

Well so now my problem. I need to have two custom controls attach to the pageLoad event.

What would be the best way of doing this?

I can't just do

old_pageLoad=pageLoad
pageLoad=function(){... old_pageLoad();}

because these custom controls can be used more than once on a page and the script needs to run for every single instance of the control, plus what if I had 3 different custom controls on the page?

the only method I've come up with is something like this which seems super hackish:

old_pageLoad_<%= MyStaticClass.GetUniqueID() %>=pageLoad;
pageLoad=function(){... old_pageLoad_<%= MyStaticClass.GetUniqueID() %>();}

Are there any better ways of handling function conflicts like this?

I have also seen this MSDN article but what it suggests doing seems worse to me than what I am currently doing.

+1  A: 

Use the RegisterStartupScript method of the ScriptManager. You pass in a reference to your control while registering the script, and that ensures that the initialization script is ran whenever the control is updated (either on the first page load, or when an UpdatePanel is updated).

Matti Virkkunen
Yea but then I have to treat my javascript as strings(in the codebehind) which means no syntax highlighting and you have to resort to either string concat or string replacement to insert server-side stuff
Earlz
@Earlz: This is why you put the bulk of your code into an external .js file and only put a simple function call (possibly with control-specific arguments) into the script for RegisterStartupString. I use a custom JS writer to build the argument strings so I don't have to worry about escaping and whatnot.
Matti Virkkunen
@Matti I try to do this already but when I need to read the value of like 10 different things, 10 arguments for a function is a bit long.
Earlz
Earlz: That's still how it works. Pass in an object or an array if you have a lot of params.
Matti Virkkunen
A: 

Another way would be to add a handler that calls a Javascript method when an async postback ends. I've done this on several occasions to re-initialise jQuery dialogs. E.g.

$().ready(function() {
  myInitMethod();
  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(myInitMethod);
});

function myInitMethod() }
  // Init code
}
Phil Hale