简体   繁体   中英

Rails link_to: Do something after confirmation

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?

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

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.

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

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...)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM