rails/jquery-rails

`$.rails.disableElement` is not preventing further clicking

sobrinho opened this issue · 4 comments

Hi guys,

I'm almost sure that when I call $.rails.disableElement the given element must not accept further clicking.

Take a look on this Fiddle: http://jsfiddle.net/KvSS3/1/

On the first click, the text is changed to Loading... as specified on data-disable-with but if you click again, the click is not prevented.

I'm using the master version like on Fiddle.

You're partially right in that the way it works for links isn't quite that simple. But the jsfiddle is flawed, I'll explain why.

The $.rails.disableElement function is meant to map to the disabled HTML attribute. It also updates the element with custom disabled text if specified, but the primary function was to disable the element.

The thing is, links don't have a disabled property. So for links, what has to be done is when the link is "disabled" (i.e. not really disabled since there's no such thing for links, but that's what we'll call our custom disabled state), we bind a handler to the click event (you can see that here), which prevents the link from being submitted and also prevents event propagation to the next node. Then when you call $.rails.enableElement, we remove that click binding.

What your jsfiddle is doing though, is it's also binding directly to the element's click event. Not only that, but you're binding to that link's click event before calling disableElement which in turn binds our click handler that prevents further clicks. Because your event is bound first, it will always get called before the disabled click handler that prevents clicking.

In short, the way your code works is, every time the link is clicked, your handler runs, which re-disables the link preventing further clicks during that event propagation, and then re-fires the alert box.

I'd suggest reading this article I wrote which explains a bit better about event propagation and binding.

Also, if you do find an issue, post over on rails/jquery-ujs, as this is just the ruby gem that pulls that library into rails, it doesn't actually handle the ins and outs of the javascript.

@JangoSteve I think if we add a CONTRIBUTING.md, GitHub will mention it when reporting an issue. The README explains to report these sorts of things in rails/jquery-ujs, but for some reason people keep missing that.

Whoa I had never heard of that, that looks really useful.

@JangoSteve I have no idea why I opened the issue here instead of jquery-ujs, I think I misspelled the github repository, sorry about that.

What you said about the events makes sense, thanks!