Rails provides different ajax events out of the box. (More info can be found here — https://github.com/rails/jquery-ujs/wiki/ajax, source code can be found here — https://github.com/rails/jquery-ujs/blob/master/src/rails.js#L125)
Now I have a custom widget which has two _on()
methods defined. Here is code fragment that is relevant:
_create: function() {
this._on(this.document, {
"ajax:beforeSend #some-form": function(event, xhr, settings) {
return console.log("Before send");
}
});
this._on({
// Event listeners for widget local events
});
}
I came to the point where I can have two _on()
methods and both are working. First one listens to all events that happen inside document
(so if I had something really trivial like click *
event — it will work) and second one listens only to events fired within the widget.
If I bind rails callback directly to an element in the $(document).ready
function everything works fine. Problems start when I try to add the event listener for rails ajax:beforeSend
, ajax:success
and other similar events into the first _on()
method — it simply doesn't working.
Any ideas how to marry rails events to jquery-ui widget event listener? Thanks.
If you'll look at the code of
_on()
in jQuery UI you'll see that it uses regexp/^(\w+)\s*(.*)$/
to get event name and selector:Apparently it sees your desired
ajax:beforeSend
event as justajax
and selector like:beforeSend #some-form
and not triggering handler.It is a common practive to make event names with colon inside nowadays so it may be a good idea to send pull request.
Meanwhile you could register global handlers for desired events and retrigger them with different names without colon inside.