Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Rails UJS driver events

#5813

Hi,

Rails UJS driver generates 5 differents javascript events during an ajax call:

  • ajax:before
  • ajax:complete
  • ajax:success
  • ajax:failure
  • ajax:after

In order to react to these events, for example if you want to enable a visual feedback during a long ajax call, javascript code like this is necessary:

<%= javascript_tag do %>
        
        Event.observe('myform', 'ajax:before', function(event) {
        });
        
        Event.observe('myform', 'ajax:after', function(event) {
        });
        
        Event.observe('myform', 'ajax:success', function(event) {  
        });
        
        Event.observe('myform', 'ajax:failure', function(event) {
        });
            
        Event.observe('myform', 'ajax:complete', function(event) {
        });
    
    <% end %>

Although it works fine, it does not allow the programmer to use rails prototype and scriptaculous helpers in the events.

I came up with this small helper:

def javascript_event_tag(name, event, &block)
    content = "Event.observe('#{name}', '#{event}', function() {"
    content = content + update_page(&block)
    content = content + "});"
     
    content_tag(:script, javascript_cdata_section(content))
  end

This makes it possible to write code like:

<div id="wait" style="display:none">
    <img src="/images/ajax-loader.gif"> Please wait...
</div>

<%= link_to 'ajax call', 'code_on_controller', :id => "mylink", :remote => true %>

<%= 
   javascript_event_tag('mylink', 'ajax:before') do |page|
     page.show 'wait'
   end
 %>
 <%= 
   javascript_event_tag('mylink', 'ajax:complete') do |page|
     page.hide 'wait'
   end
 %>

I'm not sure if that would be a good idea to include this in rails, since much of the rails 2 ajax helpers have been dropped in rails 3. But in case it can help anyone, I post it here.

Reported by Philippe Lang · October 15th, 2010 @ 08:31 AM

State: invalid
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Rohit Arondekar
    Rohit Arondekar
    • State changed from new to invalid
    • Importance changed from to Low

    I'm not sure if that would be a good idea to include this in rails, since much of the rails 2 ajax helpers have been dropped in rails 3. But in case it can help anyone, I post it here.

    I'm sorry but this is the core issue tracker of Rails. This is not a place for posting workarounds for issues. If you believe this is a real issue and/or are willing to write a patch with tests please leave a comment and I'll reopen the ticket.

    October 15th, 2010 @ 10:26 AM