Rails link_to: Do something after confirmation

百般思念 提交于 2019-12-10 13:08:16

问题


I'm trying to execute a save action via AJAX using link_to:

<%= link_to 'Save', image_path(image), method: :patch, 
        data:{ confirm: 'Save image?', remote: true } %>

I want the link to be replaced with <span>Saving...</span> on confirmation, but can't figure out a clean way to do it.

Problems with existing solutions:

disable_with:
If I add :disable_with => '<span>Saving...</span>' the inner HTML of the link will be replaced instead of the link itself. Don't want that.

onclick:
If I add :onclick => "$(this).replaceWith('<span>Saving...</span>');" the link will be replaced immediately, even if the user cancels the confirmation

Is there a solution that fits with Rails 3 UJS best practices?


回答1:


You can use the hook ajax:beforeSend :

$('a#my_link_to').bind('ajax:beforeSend', function(evt, xhr, settings) {
  $(this).replaceWith('<span>Saving...</span>');
})

And then you could add a bind to ajax:success :

$('a#my_link_to')
  .bind('ajax:beforeSend', function(evt, xhr, settings) {
    $(this).replaceWith('<span id="saving">Saving...</span>');
  })
  .bind('ajax:success', function(evt, data, status, xhr) {
    $('span#saving').replaceWith('Saved!');
  })

Note: Please refer the comment below which also is very important




回答2:


I think this is a case where the functionality you want goes beyond what's offered by Rails' JS helpers. At this point I would just avoid using the :confirm and :remote options to link_to, and implement it in plain jQuery UJS or similar.

You might also think in terms of hiding the link and showing the 'Saving...' span when the user confirms, rather than replacing html; I think it will end up simpler that way, and still give you the effect you're looking for.




回答3:


I think you should use confirm:complete event. (details: https://github.com/rails/jquery-ujs/blob/master/src/rails.js)




回答4:


Here's how I ended up doing it:

<%= link_to 'Save', image_path(image), method: :patch, 
        data:{ confirm: 'Save image?', remote: true }, 
        onclick: "$(this).one('ajax:beforeSend', 
            function(e) { $(this).replaceWith('<span>Saving...</span>'); });" %>

(The problem with this solution is that the handlers accumulate if the user clicks, does not confirm, clicks again, etc... Therefore it's not ideal...)




回答5:


You can use the confirm:complete event. It gets a second boolean argument passed which tells if the result was cancel or ok.



来源:https://stackoverflow.com/questions/18447186/rails-link-to-do-something-after-confirmation

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