Prevent Rails link_to_remote multiple submits w Javascript
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!
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.
精彩评论