Ricky Nelson
Ricky Nelson

Reputation: 876

How to prevent default action with backbone?

I have a delete link in Rails:

<%= link_to "#{image_tag("icons/icon_delete.png", :alt => "Delete")} Delete".html_safe, "#suppliers", id: supplier.id, class: "delete", :title => "Delete", :confirm => 'Are you sure?', :method => :delete %>

And I have a backbone event that catches it (CofeeScript):

  events: ->
    "click a.delete": "deleteSupplier"

  deleteSupplier: (event) ->
    event.preventDefault()
    console.log("delete")

All of this works fine, except that when I click OK on the confirm dialog, the link is followed. Any ideas how to prevent this? If I return false from deleteSupplier the confirmation no longer works which isn't quite what I'm after. I'd like the confirmation to work, just not follow through the link when I click OK.

EDIT: I forgot to mention that these links are inserted after the page is loaded through an ajax get request. And I also tested by removing the :confirm and it doesn't seem to make any difference. I believe it has something to do with being loaded through the ajax request, but I would have thought that the event would not even fire if that were the case :(

Upvotes: 2

Views: 2443

Answers (1)

fguillen
fguillen

Reputation: 38772

You are playing with two forces: the Rails magic link who adds JS handlers to the link and the Backbone who also adds handlers to the link.

You better go with one and give the day free for the other. As you are using Backbone as your JS weapon let's move all the JS logic to Backbone:

<%= link_to "delete", "#suppliers", :id => supplier.id, :class => "delete", :title => "Delete" %>

deleteSupplier: function( event ) {
  event.preventDefault();
  if( confirm( "Are you sure?" ) ) {
    console.log("delete")
  }
}

Upvotes: 5

Related Questions