简体   繁体   中英

Best way of handling javascript within Custom Controls?

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.

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

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. Eg

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

function myInitMethod() }
  // Init code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM