Rails UJS “on” for handling ajax event

半世苍凉 提交于 2019-12-24 03:16:52

问题


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


回答1:


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.




回答2:


Some useful links:

Event Delegation

Understanding delegation .on()

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



来源:https://stackoverflow.com/questions/20486433/rails-ujs-on-for-handling-ajax-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!