Last Updated: February 25, 2016
·
756
· 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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside