0

ers.

I am trying to implement my custom collection where I overwrite fetch method. Later I will use this collection to extend my Backbone collections.

var BaseCollection = Backbone.Collection.extend({

    fetch: function (options) {
        options = options || {};

        if (!options.headers) {
            options.headers = {
                'Content-type': 'application/json',
                'Accept': 'application/json',
                'Authorization' : "Basic: user:password"
            };
        }

        options.reset = true;

        console.log('I am extended fetch method');

        return Backbone.Collection.prototype.fetch.call(this, options);
    }
});

var ShipsCollection = BaseCollection.extend({
    url: 'http://localhost:3000/v1/ships',
    model: Ship
});

But when I call fetch for my collection I can not see headers were sent to the server:

var shipsCollection = new ShipsCollection();
shipsCollection.fetch();

enter image description here

How can I extend fetch to be able send custome headers ? I do not want to overwrite sync.

Community
  • 1
  • 1
AlexeiBerkov
  • 427
  • 1
  • 6
  • 16

2 Answers2

2

As you can see from the fiddle shared by @nikoshr in comments, the code seems to work.

However, your code won't work in case options.headers exist. I suggest modifying the code as follows:

fetch: function(options) {
  options = options || {};
  var custom = {
    'Content-type': 'application/json',
    'Accept': 'application/json',
    'Authorization': "Basic: user:password"
  };
  options.headers = options.headers ? _.extend(options.headers, custom) : custom;

  options.reset = true;
  return Backbone.Collection.prototype.fetch.call(this, options);
}
T J
  • 42,762
  • 13
  • 83
  • 138
0

In my case it was a AdBlock plugin. When I removed it everything went fine.

AlexeiBerkov
  • 427
  • 1
  • 6
  • 16