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

Simple global override of the Backbone.sync method that formats delete requests into application/json and stringifies the data. It will be called from all CRUD functions, but it provides clean usage (can still call .destroy()) and very little overhead.

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>Overriding Backbon.sync to allow for sending data along with a DELETE request from a .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

// Save a copy of the old Backbone.sync function so you can call it later.
var oldBackboneSync = Backbone.sync;

// Override Backbone.Sync
Backbone.sync = function( method, model, options ) {
    if ( method === 'delete' ) {
        if ( options.data ) {
            // properly formats data for back-end to parse
            options.data = JSON.stringify(options.data);
        }
        // transform all delete requests to application/json
        options.contentType = 'application/json';
    }
    return oldBackboneSync.apply(this, [method, model, options]);
}

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...
someBook.destroy({ 
    data: { cover: 'hardcover' } 
});