26

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!

gcdev
  • 1,406
  • 3
  • 17
  • 30

1 Answers1

55

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.

Benjamin Atkin
  • 14,071
  • 7
  • 61
  • 60
  • Nice answer! I don't think options.params is right, though, as Backbone.sync just extends the passed in 'options', so when it looks for params.url, it's actually just options.url – satchmorun Aug 08 '11 at 20:47
  • Thanks! I was fixing my answer when you posted your comment. :) – Benjamin Atkin Aug 08 '11 at 20:50
  • Thanks -- that seems to work so far with just some minor modifications, most notably, methodUrl should have 'create' instead of 'post'. I made some other changes for my purposes, but nothing else really worth noting here. Good answer. – gcdev Aug 09 '11 at 16:22
  • You saved me about 10 hours of headache! –  Nov 28 '12 at 05:23
  • This is an incredible answer. This should be featured somewhere for Backbone devs to find. – Brandon Apr 08 '13 at 03:11
  • 1
    Thanks, Brandon. You found it! I recommend Stack Overflow to practically every developer who asks me how they can do a better job. :) – Benjamin Atkin Apr 25 '13 at 06:47