Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify various URLs in a backbone app?

Tags:

backbone.js

I need one of my backbone models to hit a variety of URLs depending on the type of action being performed. How do I determine the action within the URL function so that I can specify the appropriate URL? For example:

DELETE: /myapipath/itemtype/id/
POST: /myapipath/special-path/
GET: /myapipath/special-path/?code=ABC

I know how to tell the difference between a POST and everything else: this.isNew()

But how do I tell the difference between a DELETE and a GET in a custom model.url function?

Please don't suggest that I change the server-side api. That isn't up to me.

Thanks!

like image 229
gcdev Avatar asked Aug 08 '11 18:08

gcdev


1 Answers

Conceptually the url of a Backbone model is the primary GET url of the resource. To use a different url for some of the actions, override the model's sync function. Fortunately, Backbone makes it easy to override:

window.MyModel = Backbone.Model.extend({   // ... other stuff ...    url: '/myapipath/special-path/?code=ABC',    methodUrl: {     'create': '/myapipath/special-path/',     'delete': '/myapipath/itemtype/id/'   },    sync: function(method, model, options) {     if (model.methodUrl && model.methodUrl[method.toLowerCase()]) {       options = options || {};       options.url = model.methodUrl[method.toLowerCase()];     }     Backbone.sync(method, model, options);   } } 

Edit: I took another look at the Backbone source and noticed that it merges the whole options argument to build the params, not options.params, and updated my example accordingly.

like image 57
Benjamin Atkin Avatar answered Oct 04 '22 13:10

Benjamin Atkin