Extend Backbone model save

backbone.js, javascript

Solution

Backbone's save and fetch methods just make calls to the Backbone.sync method, which in turn is just a wrapper for an ajax call. you can pass in ajax parameters using the save function without having to actually extend it. basically ends up being something like this:

game.save({attributes you want to save}, {type:'POST', url: 'apiurl/model/:id/played'});

You would have to do this every time though so it is probably better practice to extend Backbone.sync for your model.

The Backbone website has a bit of information about what I'm talking about as far as the Backbone sync and save taking ajax options. There are also a few examples I've seen on extending sync but I can't seem to track them down at the moment.

Problem

What is the best way to extend the `model.save` method? I need to add new methods to post same data to backend. i.e.: `played` method should request (by POST) to `apiurl/model/:id/played` e.g.: ``` var Game = Backbone.Model.Extend({ baseUrl: '/games/', played: function(){ this.url = this.baseUrl + this.id + '/played' this.save(); } }); var game = new Game({id:3234}); //is only an example, instances are created before previuosly game.played(); ``` This way is working but the request is a GET. In addition, it would be perfect if this `save()` did not send all the attributes in the request. Adding information: As I have to interact with cross domain api, I've extended the sync method in order to work with JSONP. Moreover, I've added some security instructions. ``` //backbone sync Backbone._sync = Backbone.sync; Backbone.sync = function(method, model, options) { //network options.timeout = 10000; options.dataType = "jsonp"; //security if(_conf.general.accessToken){ var ak = _conf.general.accessToken, url = model.url, linker = url.indexOf('?') === -1 ? '?':'&'; model.url = url + linker + 'accessToken=' + ak+'&callback='; } //error manager var originalError = options.error || function(){}; options.error = function(res){ originalError(res.status, $.parseJSON(res.responseText)); }; //call original Method Backbone._sync(method, model, options); }; ```

Original source