A while ago I blogged about Combining jQuery and Ms Ajax UpdatePanels. (http://bloggingdotnet.blogspot.com/2009/03/combining-jquery-and-updatepanels.html). The main problem is that the UpdatePanel contents (a Div element) are replaced during each post back from the server and this means that jQuery looses all the references to the elements that have now been replaced in the DOM. My initial work around (and commonly found on the internet) is a little clumsy as it involves hooking the Ms Ajax pageLoad event and placing all your jQuery code in a separate function which is then called from $(document).ready or pageLoad. Not pretty and not clever, especially when you have lots of jQuery and you only want to rerun the jQuery for the panel that has actually changed.
My subsequent workarounds involved looking into the LiveQuery plug-in and looking at Live events which are new to jQuery 1.3, however I wasn't satisfied with the performance, and the code still looked ugly. And when it looks ugly that usually means there is a better way. What I wanted was code that looked and worked like any other jQuery plug-in. I needed to dig more deeply into the Ms Ajax client runtime. What I found was the PageRequestManager which is created once per page by Ms Ajax and fires the pageLoaded event on each post back. Hooking into this event allows us to examine the panels that have been updated or created. Using this information, it was then relatively straightforward to wrap a jQuery-style functional interface around these events.
The UpdatePanel plug-in has the following three callbacks:
- .panelCreated(fn) - called when the UpdatePanel is created on a page
- .panelUpdated(fn) - called when the panel is updated during a asynchronous (ajax) postback.
- .panelReady(fn) - called when the UpdatePanel is first created or updated
You would generally use the panelReady event like so:
$(document).ready(function() { //Place jQuery code here for elements selected outside the update panel $('#UpdatePanel1').panelReady(function() { //Place jQuery code here for elements selected inside the update panel }); });
Generally, you would only want to use panelReady, which is called when the page is first loaded, or on each postback. A sample project as well as the script is available at http://updatepanelplugin.codeplex.com/ or http://plugins.jquery.com/project/updatepanelplugin
No comments:
Post a Comment