Send a data payload along with a delete request from a Backbone.Model

Done by passing specific AJAX options in to the .destroy() call. It's a little gross because it exposes you to the underlying AJAX workings which should be kept abstracted. It's good because it's a quick fix and requires very little additional code.

by Cory Danielson

HTML

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<h1>Sends data to back-end with a DELETE request by explicitly passing the AJAX options to the model's destroy call.</h1>
<h2>(chrome) To see if this request is working, open your developer panel and click the network tab and run the code. Click on the delete request and inspect the Headers</h2>
<h3>You should see something like this.</h3>
<table>
    <tr>
        <th>Good Request</th>
        <th>Bad Request (without backbone.sync override)</th>
    </tr>
    <tr>
        <td><img src="http://i42.tinypic.com/5nkv1k.png"></img></td>
        <td><img src="http://i43.tinypic.com/j1229v.png"></img></td>
    </tr>
</table>

CSS

h1 { border-bottom: 1px dotted red; }
h2 { border-bottom: 1px dotted salmon; }
h3 { border-bottom: 1px dotted lime; }

JavaScript

// Extend from the enhanced model so that you can get the overridden sync method
var Book = Backbone.Model.extend({
    urlRoot: 'api/book',
    defaults: {
        id: 1,
        title: 'Backbone.js Help'
    }
});

var someBook = new Book();

// Maybe you want to only delete hardcover copies from the db? Who knows...
// This usage is a less clean than just calling someBook.destroy(options)
someBook.destroy({
    contentType: 'application/json',
    data: JSON.stringify({ cover: 'hardcover' })
});