views:

55

answers:

2

I have migrated frameworks from prototype to jQuery in my Rails apps, and I'm running into a consistent problem which I need some advice on.

Often times I'll use an AJAX function that updates a portion of the page. When this happens, any other Javascript I use that relates to the section of the page that was updated no longer works. What's the best way around this?

Most of my javascript lives inside jQuery(document).ready(function() { }); with some functions that live outside this method. I've been getting around this by relying on the jQuery .live() handler, or by calling the function I want to 'reinitialize' in my js.erb files.

What's the best approach? Should I:

  • explicitly call functions by name to work as part of the callback to get them to work
  • continue to use the .live() for submit/click events
  • or is there better, more efficient way to deal with this

Looking forward to your feedback everyone and thanks for your advice.

-A

A: 

aressidi - you could also use .livequery() as this encapsulates .live() with a few additional bells and whistles for callbacks etc. also, consider using .unbind() for certain event handlers (such as toggle etc).

more info here: http://docs.jquery.com/Plugins/livequery

jim

jim
Hi Jim, thanks for your response. I got things mostly working based on your answer and nicholasklick's below. I realized that it was toggle that was causing problems after replacing a portion of the page with AJAX. I found a post on how to create your own toggle handler and encapsulate it in .live(). Here's the link: http://stackoverflow.com/questions/2172614/using-jquery-live-with-toggle-event. The only problem is that it only works for one cycle - show and hide. If I click it again, nothing happens. Any idea why that is?
aressidi
A: 

In your callbacks use trigger() to trigger events. Use live() for events bound to areas of the DOM that are being updated.

I always use this pattern:

Ajax:

$(.link).live("click", function(){
  $.ajax({
        url: '/controller/action',
        success: function(response){
        $(document).trigger("event_name", ["method", response]);
        $('.class').html(response.html);
        }
    }); 
})  

Rails action (rerender content of a partial):

class Controller < ApplicationController

def action
    render :json => {
          :html => render_to_string(
            :partial => 'partial_name', 
            :locals => {:var => @var}
          )
        }
end
nicholasklick
Hi Nicholasklick, thanks for your answer. I posted a follow-up under Jim's answer above that you might be able to help with as well. Both of your answers have come in handy. Thanks again
aressidi