0

In a Rails project I need to keep a link_to_remote from getting double-clicked. It looks like :before and :after are my only choices - they get prepended/appended to the onclick Ajax call, respectively. But if I try something like:

:before => "self.stopObserving()"

the Ajax is never run. If I try it for :after the Ajax is run but the link never stops observing.

The solutions I've seen rely on creating a variable and blocking the whole form, but there are multiple link_to_remote rows on this page and it is valid to click more than one of them at a time - just not the same one twice. One variable per row declared outside of link_to_remote seems very kludgey...

Instead of using Prototype I originally tried plain Javascript first for this proof of concept - but it fails too:

<a href="#" onclick="self.onclick = function(){alert('foo');};">click</a>

just puts up an alert when clicked - the lambda here does nothing? This next one is more like the desired goal and should only alert the first time. But instead it alerts every time:

<a href="#" onclick="alert('bar'); self.onclick = function(){return false;};">click</a>

All ideas appreciated!

Chris
  • 1
  • 2

1 Answers1

0

I got this to work using jQuery:

link.click(function() { 
  alert('foo'); 
  $(this).unbind('click'); 
  $(this).click(function() { 
    return false; 
  }); 
  return false; 
})

So surely you can accomplish the same with plain old javascript.

The benefit of doing this with jQuery is that it would be easy to add a class to all links that you want to behave this way and in your application.js you could assign this behavior to all links of that class.

Of course, you can do all that with plain old JavaScript too... jQuery just makes it easier.

Samo
  • 8,202
  • 13
  • 58
  • 95
  • Having trouble making that into an inline call. In fact Firebug in FF3.6 claims there is no $(this).unbind with jQuery 1.3, though "unbind:function" appears in the file. StackOverflow click – Chris Dec 24 '10 at 14:26
  • I suggest you avoid inline calls. jQuery is all about unobtrusive JavaScript. If you put this in a JavaScript file that will be loaded by all pages, you can assign this behavior to all links of a certain class. I also suggest you upgrade to a newer jQuery – Samo Dec 29 '10 at 19:22