Search code examples
backbone.jsbackbone-routing

Using Backbone to FETCH a model using the OPTION verb


I am using Backbone with a RESTful interface that is provided by a 3rd party (so I can not change it).

For one of the models (which is read only) the RESTful interface states that you use the HTTP OPTIONS verb not the GET verb. Can I tell backbone to use "OPTIONS" not "GET" just for that model as other models use GET


Solution

  • You should be able to do something like this in your model definition:

    sync: function(method, model, options){
      if(method !== "read") throw "Read-only model cannot be called with non-read method";
    
      options || (options = {});
      var params = {type: "OPTIONS", dataType: 'json'};
    
      if (!options.url) {
        params.url = _.result(model, 'url') || urlError();
      }
    
      var xhr = options.xhr = Backbone.ajax(_.extend(, options));
      model.trigger('request', model, xhr, options);
      return xhr;
    }
    

    In opther words, you need to rewrite the sync method for your model so it behaves like you want it to (i.e. sending OPTIONS verb). Take a look at Backbone's sync implementation for inspiration: http://backbonejs.org/docs/backbone.html#section-143