This project is archived and is in readonly mode.

#5813 ✓invalid
Philippe Lang

Rails UJS driver events

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

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.

Comments and changes to this ticket

  • Rohit Arondekar

    Rohit Arondekar October 15th, 2010 @ 10:26 AM

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

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Pages