开发者

Ruby on Rails3: How do I invoke javascript before an ajax event is fired with remote => true?

        <%= link_to( {:controller => 'board', 
                          :action => 'take_turn', 
                          :id => @board.id,
                          :x => col, 
        开发者_如何学Python                  :y => row} , :remote => true, :onClick => "return links_disabled;") do %>
          <div class="ttt_square"> 
            &nbsp;
          </div>
        <% end %>

in rails2, there were :before, and :complete params, but I have not found any documentation for this in rails3


As I understand it, this is one of the consequences of Rails 3 using UJS (unobstrusive javascript). Rails 3 enables you to keep the javascript away from e.g. a link-tag. Instead of the link-tag specifying what should be done via javascript, you make the javascript observe the link-tag.

You achieve this by binding a function to a certain event of an object, eg. binding the ajax:before event of the link-tag to a function.

In this blog post the author explains how to do it, in his case with JQuery.


As far as I understand, in Rails 3 you bind the callback events to the element on the client side, and they are fired by rails.js at the appropriate times.

$('#myform').bind('ajax:success', function(){
    alert('I succeeded');
})


If I remember well, there is no more support in Rails3.

You could use native jQuery function:

ajaxStart()

http://api.jquery.com/ajaxStart/

See details here: http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/


My version (jquery-rails 0.2.6) supports ajax:before, loading, success, complete, failure, and after. The parameters to the success/failure functions are not the same which has tripped me up in the past. But the following works for me:

$('a').bind('ajax:loading', function() {
  alert('here');
});

If your link element was created after the initial page load, you might need to bind using 'live':

$('a').live('ajax:loading', function() { alert('...'); });

I would also double-check that your onclick handler is not interfering.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜