views:

2338

answers:

4

Hi,

How can I rebind my events (jquery) when I perform a partial page postback?

I am wiring everything up using:

$(document).ready(function(){};

After a partial page postback, my events are not firing.

+2  A: 

I'm guessing from 'partial page postback' you're working in Asp.net land.

Try using Sys.Application.add_load(function() { });

You should still be able to use all the normal jQuery stuff inside that func.

ecoffey
Exactly. That's exactly why MS invented that load event: they knew they'd be blowing away DOM elements after partial postbacks, and they needed to give devs a single way to do stuff when the page is ready, regardless of whether fancy AJAX UpdatePanels are used or not.
JPot
A: 

Some DOM elements are replaced when you do a partial postback, and of course, the new elements will loose jQuery bindings. You can use the ScriptManager class to register a script that will be executed after the partial postback finishes (have a look here)

ybo
+4  A: 

You can either tap into the PageRequestManager endRequestEvent:

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

Or if it is control events you're trying to attach, you can use jQuery live events.

Another option is to do the event delegation manually. It is what the "live" event are doing under the covers. Attach the event handler to the document itself, then conditionally execute your method if the sender of the event was element you expect.

$(document).click(function(e){  
    if($(e.target).is(".collapseButton")){  
        $(this).find(".collapsePanel").slideToggle(500);  
    }  
})
Mark
thanks that worked, guess it is not as effecient but its only for this one page.
Blankman
It is actually very efficient. If you have event handlers on every row of a grid, this will have only one event handler for the entire grid. It gets even better if you have several event handlers for each row. You can get by with only one....and nothing to attach to new records created manually or via partial postbacks.
Mark
+1  A: 

Check out the "live" feature of jQuery 1.3 here. You can add events to future elements as well as current elements on the page. This may simplify the code you'll need to write.

Brandon Montgomery
we are not using 1.3 so cnt' use live.
Blankman
We use "live" events a lot, but sometimes they don't meet out needs. If you're using jQuery to manipulate the DOM, you'll need to re-manipulate it after it's been updated via the partial postback.
Mark
You can achieve the same effect of live by doing the event delegation manually.
Mark
how can I do this manually?
Blankman
I remember attempting to use that, but it doesn't fully work for IE, and <asp:UpdatePanel /> breaks some of it.
ecoffey
Thanks all - good to know. I've never actually tried to use it, I just knew it was something that was new in jQuery 1.3.
Brandon Montgomery