Question

I'm using Rails with UJS. I want to bind some events to disable an ajax link before submission, and reenable it in the event of an error. I wrote this jQuery to handle the process:

$('.post').on('click', 'a[data-toggle="follow"]', function() {
  var elem, href;
  elem = $(this);
  href = elem.attr('href');
  return elem.bind('ajax:loading', elem.attr('href', '#')).bind('ajax:error', elem.attr('href', href));
});

When I deliberately simulate an exception in my controller, I get this JS error:

Uncaught TypeError: Object [object Object] has no method 'apply'

Any idea why this is happening? The Ajax itself works fine. It's only when there's a server error that this happens.

li.subscription
  - if signed_in? && current_user.subscribed?(post)
    = link_to "Unfollow", [post, current_user.subscriptions.find_by_post_id(post)], method: :delete, remote: true, 'data-toggle' => 'follow'
  - else
    = link_to "Follow", post_subscriptions_path(post), method: :post, remote: true, 'data-toggle' => 'follow'
Was it helpful?

Solution

The jQuery bind function takes a handler function as the second argument. However here you are providing it with a jQuery object instead (i.e. the value which is returned by elem.attr('href', '#')).

You need something like:

return elem.bind('ajax:loading', function() {
    elem.attr('href', '#');
}).bind('ajax:error', function() {
    elem.attr('href', href);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top