Search code examples
javascriptbackbone.js

Backbone Models - change URL query params depending on REST action


Inside a Backbone model, we have the url and urlRoot attributes:

           url: function(){

               return '/jobs'
            },


            urlRoot: function () {

                return '/jobs'
            },

however I want to add params or query params to the url, depending on what type of request it is GET, POST, PUT, DELETE, etc.

So I want to do something like this:

     url: function(type, opts){ //type and opts arguments are not available in Backbone, I just made them up for this example

          var url = '/jobs';

           switch (type) {
              case 'GET':
                break;
              case 'POST':
                break;
              case 'PUT':
                url = url + '?optimisticDelete=' + opts.optimisticDelete;
                break;
              case 'DELETE':
                url = url + '?upsert=' + opts.upsert;
                break;

               default:
                 throw new Error('no match');
                }

          return url;
    },

is there a good way to accomplish something like this?


Solution

  • By default, Backbone models and collections delegate to the Backbone.sync function to interact with the server. That's the scope where you will have access to the HTTP method like in your example. You can override the sync function on a model or collection to customize this behavior. Check out the documentation and source code for Backbone.sync and for jQuery.ajax, which Backbone.sync uses.

    I haven't touched Backbone or JavaScript in a while, but I would imagine it would look something like this (this is basically pseudo-code, don't expect it to work as written):

    sync: function (method, model, options) {
        // method corresponds to the HTTP verb ("type" in your example)
        switch (method) {
          // ...build the correct url like in your example...
        }
        options = options || {};
        options.url = url; // tack correct url onto options object
        return Backbone.sync.apply(this, [method, model, options]);
    }
    

    It will most likely take more fiddling than this, but hopefully it gets the point across.