documentcloud/backbone — pull request #2494 by runemadsen (2013-04-20 15:50:00+00:00)
Title: add if statement and add passing test

This has been discussed in https://github.com/documentcloud/backbone/pull/1686, but I'm going to try to explain why I think my tiny change matters.

I often find myself overriding the `Backbone.sync` method, in order to set custom headers, etc. For example, to use the Github API, I need to do something like this:

```javascript
GitHub.sync = function(method, model, options) {
var extendedOptions;
extendedOptions = _.extend({
beforeSend: function(xhr) {
xhr.setRequestHeader('Accept', 'application/vnd.github+json');
if (GitHub.token) {
return xhr.setRequestHeader('Authorization', "bearer " + GitHub.token);
}
}
}, options);
return Backbone.sync(method, model, extendedOptions);
};
```

I often find myself wanting to call the `Backbone.sync` method directly, so I can use it outside a specific model or collection, like this:

```javascript
Backbone.sync('read', false, {url : "someurl", data : ""})
```

As discussed in https://github.com/documentcloud/backbone/pull/1686, Backbone.sync now requires a model to work. That's because of a single `model.trigger` call, as backbone.sync will correctly check for the existence model on all other occasions, and pull all of the needed data from the `options` if they exist. Except for this one line.

First question you might ask: Why not just use `jQuery.ajax`?

Well, because `Backbone.sync` handles a lot of stuff for me, and I already extended it to work with the API I'm talking to. Besides that, the functionality to check for whether the model exist is already implemented other places in the `Backbone.sync` method. This is not changing the way it works already.

Second question you might ask: Why can't you use a model or collection?

An example of this would the Github contents API, which doesn't conform to REST, as it can return an object or an array of objects on the same API endpoint. In this case, I don't know if I need a collection or a model, and I therefore use Backbone.sync to load the result, and then instantiate the needed object.

I made the proposed file changes and added a test that fails without, and passes with my proposed file change.

Let me know what you think.