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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With