Search code examples
restbackbone.js

Backbone.js Model different url for create and update?


lets say I have a Backbone Model and I create an instance of a model like this:

var User = Backbone.Model.extend({ ... });
var John = new User({ name : 'John', age : 33 });

I wonder if it is possible when I use John.save() to target /user/create when I use John.save() on second time (update/PUT) to target /user/update when I use John.fetch() to target /user/get and when I use John.remove() to target /user/remove

I know that I could define John.url each time before I trigger any method but I'm wondering if it could be happen automatically some how without overriding any Backbone method.

I know that I could use one url like /user/handle and handle the request based on request method (GET/POST/PUT/DELETE) but I'm just wondering if there is a way to have different url per action in Backbone.

Thanks!


Solution

  • Methods .fetch(), .save() and .destroy() on Backbone.Model are checking if the model has .sync() defined and if yes it will get called otherwise Backbone.sync() will get called (see the last lines of the linked source code).

    So one of the solutions is to implement .sync() method.

    Example:

    var User = Backbone.Model.extend({
    
      // ...
    
      methodToURL: {
        'read': '/user/get',
        'create': '/user/create',
        'update': '/user/update',
        'delete': '/user/remove'
      },
    
      sync: function(method, model, options) {
        options = options || {};
        options.url = model.methodToURL[method.toLowerCase()];
    
        return Backbone.sync.apply(this, arguments);
      }
    }