Rails UJS confirm box cancel button callback

允我心安 提交于 2019-12-10 14:57:00

问题


I am using Rails jquery ujs for handling ajax within my app. Also I am using a the confirm option for destroying any records. As my current setup, I have hooked up a loading overlay screen on click of data-remote=true link.

All I wanted to know is: Is there a way I can hook a callback event when a user clicks cancel on the confirm box and I can close the loader overlay.


回答1:


Yes, you can. Pass in the response object. In CoffeeScript.

  $('selector').on 'confirm:complete', (e, response) ->
    if response
      # User confirmed
    else
      # User cancelled.

In Javascript:

  $('selector').on('confirm:complete', function(e, response) {
    if(response) {
      // User confirmed
    }
    else {
      // User cancelled.
    }
  });



回答2:


For those of you stumbling on this question and using Rails >= 5.1, note that the callback parameters have been bundled into event.detail, which is an array. The first callback parameter is event.detail[0] and so on.

To update Mohamad's answer, here's how to check the confirm value in Rails >= 5.1.

$('selector').on('confirm:complete', function(e) {
  if (e.detail[0]) {
    // User confirmed
  }
  else {
    // User cancelled.
  }
});

From Rails Guide:

Rails 5.1 introduced rails-ujs and dropped jQuery as a dependency. [...] Unlike the version with jQuery, all custom events return only one parameter: event. In this parameter, there is an additional attribute detail which contains an array of extra parameters.



来源:https://stackoverflow.com/questions/19516654/rails-ujs-confirm-box-cancel-button-callback

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