Rails :confirm modifier callback?

我是研究僧i 提交于 2019-12-04 10:29:56

问题


I want to call a javascript function that will be conditional upon a user's response to the confirm box.

For example, I have the following anchor:

<%= link_to 'Sign Out', destroy_session_path, confirm: 'Are you sure that you would like to sign out?', method: :delete %>

Should I just abandon the unobtrusive javascript and bind my own jQuery callback to my anchor?

Or is there some magical way to pass a callback function to the Rails url helper? I did not see any discussion of callbacks in the documentation.


回答1:


By following the link_to source, I see that the :confirm modifier is passed to the convert_options_to_data_attributes method, which points to the ujs script that is bundled with Rails these days (the unobtrusive javascript via jQuery). Here we find that ultimately the user's response is passed to an event called confirm:complete by using the data-confirm attribute in the html.

So it appears that the answer is "no, you cannot pass a callback through the url helper". But you can put a callback in your app/javascript to listen for this event. This seems to be the most unobtrusive way to accomplish my goal, considering that I am still letting rails handle the event prevention and propagation. I wait for all of this to happen, and then call my function.

$(document).on('confirm:complete', function (e, answer) {
  if (answer) {
    // user confirmed!
    myCallbackFunction();
  } else {
    // user canceled!
  }
});



回答2:


I had a similar issue (How to use inline :confirm option for html helpers with AJAX calls?). @Micah's answer, even though works, is not what "Rails 3 way" would be.

  1. remote: true option needs to be added to the link_to helper, e.g.

link_to 'Sign Out', destroy_session_path, remote: true, confirm: 'Are you sure that you would like to sign out?', method: :delete

  1. In the controller change respond_to block to answer to js

  2. create a js file with the name that corresponds to your method, e.g. destroy_session.js.coffee

app/views/competitions/destroy_session.js.coffee:

jQuery ->
  $("form[data-remote]").on "ajax:success", (e, data, status, xhr) ->
    $(e.currentTarget).closest('tr').fadeOut()`

Hope that helps



来源:https://stackoverflow.com/questions/13224482/rails-confirm-modifier-callback

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