Rails :confirm modifier callback?

前端 未结 3 474
遥遥无期
遥遥无期 2021-02-08 01:54

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:

<%         


        
3条回答
  •  再見小時候
    2021-02-08 02:15

    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!
      }
    });
    

提交回复
热议问题