Search code examples
ruby-on-railsrubycoffeescriptcocoon-gem

Ruby on Rails 4 and cocoon gem : How to interrupt deletion on cocoon:before-remove


I'm looking for a way to do a more sophisticated confirm that the one I use right now that look like this :

     <%= link_to_remove_association "<i class='icon-remove-sign'></i>".html_safe, 
      p, :class => 'btn-link remove has-tooltip',
     :data => {:original_title => "Delete phone", 
     :confirm => 'Are you sure you want to delete this phone?'} %>

I just want to avoid the confirm dialog if the phone entry is blank.

I think there must be a way in the 'cocoon:before-remove' event but I can't manage to find it ?

For example, in a Coffesecript function like this :

$(document).delegate '.phones', 'cocoon:before-remove', (e, item) ->

    tel = $(item).find('.tel .form-control')
    conf = true
    if tel.val().trim() != ''
      conf = confirm('Are you sure you want to delete this phone?')

    if conf
      $(@).data('remove-timeout', 1000)
      item.fadeOut('slow')
    else
      #stop deletion!!

    conf

Any clue ?


Solution

  • It seems that cocoon is missing this functionality, however I just forked the repo and added it. For now, you can do as follows:

    Change in your gemfile:

    gem 'cocoon', git: 'https://github.com/BroiSatse/cocoon.git'
    

    Then modify your handler:

    $(document).delegate '.phones', 'cocoon:before-remove', (e, item, result) ->
    
      tel = $(item).find('.tel .form-control')
      conf = true
      if tel.val().trim() != ''
        conf = confirm('Are you sure you want to delete this phone?')
    
      if conf
        $(@).data('remove-timeout', 1000)
        item.fadeOut('slow')
      else
        result.val = false
    

    Note the extra param for the handler.