Rails UJS “on” for handling ajax event

2019-07-10 17:45发布

I'm using the jQuery method "on" in a Rails app to attach an event on a form which doesn't always exist. It doesn't seem to be attaching an event handler when #myForm is appended to the document.

Here is UJS's suggested usage of on():

$("#myForm").on("ajax:complete", function(xhr, status) { ... }

Here is how I usually implement jQuery's on(), but this does not seem to work:

$("body").on("ajax:complete", "#myForm", function(xhr, status) {...}

Rails UJS wiki: https://github.com/rails/jquery-ujs/wiki/ajax

2条回答
孤傲高冷的网名
2楼-- · 2019-07-10 18:35

UJS doesn't really have much to do with the on function. That's provided by jQuery, and it takes multiple forms. UJS simply fires the ajax:complete event so you can hook into it yourself.

The selector argument is optional, so both

$(...).on("ajax:complete", function(xhr, status) { ... }

and

$(...).on("ajax:complete", "form", function(xhr, status) { ... }

are valid uses, though they work somewhat differently.

查看更多
神经病院院长
3楼-- · 2019-07-10 18:36

Some useful links:

Event Delegation

Understanding delegation .on()

$(selector).on(event,childSelector,data,function,map)

enter image description here

查看更多
登录 后发表回答