jfmzhq
Last Updated: February 25, 2016
·
354
· cmaher

Stop making duplicate requests in Backbone

Use Backbone.Hoard to prevent duplicate requests and cache data locally.

var cacheControl = new Backbone.Hoard.Control();
var MyModel = Backbone.Model.extend({
  url: function () {
    return '/my-models/' + this.id;
  },

  sync: cacheControl.getModelSync()
});

var model1 = new MyModel({ id: 1 });
var model2 = new MyModel({ id: 1 });

var fetches = [model1.fetch(), model2.fetch()];

 Promise.all(fetches).then(function () {
    // model1 and model2 have the same attributes,    returned from the endpoint
    // Only one ajax request has been made
   doStuff();
});

Learn about the reasoning behind it