Search code examples
node.jsbackbone.jsexpress

How to override GET arguments approach in BackboneJS on fetch?


I have the following Collection:

var collection = Backbone.Collection.extend({
   url: '/documents/'
});

When I do fetch, I need ro pass additional agrument to my query. When I do the following:

var collection.fetch({
    data: {
       key: 2
    }
});

Issied request is:

GET: /documents/?key=2;

But I need to use expressjs approach to my query will:

GET: /documents/key/2

How could I make it?


Solution

  • You can override collection's fetch method

    var collection = Backbone.Collection.extend({
         fetch: function(options) {
              if (options.data) {
                   options.url = '/documents/key/' + options.data.key;
                   delete options.data;
              }
              Backbone.Collection.prototype.fetch.call(this, options);
         }
    });
    

    Here, we just manually set url everytime we do a fetch, and delete that data property in case the $.ajax behind the scene takes it to construct a url with question marks.

    Internally, Backbone.sync() is what happens when we call fetch(), save(), and destroy() on models, and fetch() and create() on collections.

    You can see the source http://backbonejs.org/docs/backbone.html#section-141 here:

    if (!options.url) {
      params.url = _.result(model, 'url') || urlError();
    }
    

    So instead of using the url on model (which is set dependently on the model's collection, you can see the url on model in source too), we explicitly set the url ourselves.

    And in the end:

        var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
    

    As you can see, now $.ajax uses options.url instead.