Rails:确认修饰符回调? [英] Rails :confirm modifier callback?

查看:83
本文介绍了Rails:确认修饰符回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个JavaScript函数,该函数将以用户对确认框的响应为条件.

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

例如,我有以下锚点:

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

我应该放弃不引人注目的JavaScript并将自己的jQuery回调绑定到锚点吗?

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

还是有一些神奇的方法将回调函数传递给Rails url帮助器?我没有在文档中看到有关回调的任何讨论.

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.

推荐答案

通过跟随link_to源,我看到:confirm修饰符传递给了 ujs脚本(通过jQuery提供的实用Java脚本).在这里,我们发现最终用户的响应是通过使用html中的data-confirm属性传递给名为confirm:complete的事件的.

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.

因此,答案似乎是不,您无法通过url帮助器传递回调".但是您可以在app/javascript中放置一个回调以侦听此事件.考虑到我仍在让Rails处理事件的预防和传播,这似乎是实现目标的最简单的方法.我等待所有这些事情发生,然后调用我的函数.

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

这篇关于Rails:确认修饰符回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆