If you’re reading the source you probably already have a working solution. You essentially have two options (probably more)-
- Pass URL in save()/fetch()
save() takes two parameters attr and options
attr – is a hash of model attributes and is used to update the model before save.
eg.
myModel.save(attrs)
is equivalent to
myModel.set(attrs)
myModel.save()
The second parameter is an options hash, which is passed down to this.sync() (and then Backbone.sync and then $.ajax) – setting the url in this hash will work as expected.
You can pass false, undefined, or {} as the first parameter to skip the update.
- Override Backbone.sync
Rather than have url’s scattered throughout your code every time you call save() or fetch() write your own sync function to compute the url for you, the delegate to the original Backbone.sync to do the heavy lifting
eg. (This sync function adds /save to the url on CREATE, UPDATE and DELETE actions)
function mySyncFunction(method, model, options){
if(method=='GET'){
options.url = model.url;
}else{
options.url = model.url + '/save';
}
return Backbone.sync(method, model, options);
}
To use your custom sync method just declare it as part of your model
var myModel = Backbone.Model.extend({
...
"sync": mySyncFunction,
...
});