Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Backbone identity map

603 views

Published on

  • Be the first to comment

  • Be the first to like this

Backbone identity map

  1. 1. Identity Maps & Backbone Ben Teese, Shine TechnologiesThursday, 14 February 13
  2. 2. Overview The Problem About Identity Maps Backbone.IdentityMapThursday, 14 February 13
  3. 3. A DemoThursday, 14 February 13
  4. 4. Thursday, 14 February 13
  5. 5. Thursday, 14 February 13
  6. 6. Thursday, 14 February 13
  7. 7. The Problem fetch fetch Todd Roger Roger Collection ... Michael GET /suspects/1 GET /suspects BackendThursday, 14 February 13
  8. 8. What we want fetch fetch Todd ... Roger Collection Michael GET /suspects/1 GET /suspects BackendThursday, 14 February 13
  9. 9. Identity MapsThursday, 14 February 13
  10. 10. Identity Map Suspect:1 Roger Suspect:2 Todd Suspect:3 Michael Suspect:4 Fred ... ...Thursday, 14 February 13
  11. 11. Object Creation if class and ID is in identity map return the cached object else create new object put it in identity map return the new object endThursday, 14 February 13
  12. 12. Backbone.IdentityMap Backbone ‘Plugin’ Overrides Model Constructor Does not alter original BackboneThursday, 14 February 13
  13. 13. Before ... var Suspect = Backbone.Model.extend({ ... }); var Suspects = Backbone.Collection.extend({ model: Suspect, url: "/suspects" }); ...Thursday, 14 February 13
  14. 14. After ... var Suspect = Backbone.IdentityMap( Backbone.Model.extend({ ... }) ); var Suspects = Backbone.Collection.extend({ model: Suspect, url: "/suspects" }); ...Thursday, 14 February 13
  15. 15. Thursday, 14 February 13
  16. 16. How does it work? Backbone.IdentityMap = function(originalConstructor) { var newConstructor = _.extend(function(attributes, options) { // Execute our identity map logic ... return newOrCachedObject; }, originalConstructor); return newConstructor; };Thursday, 14 February 13
  17. 17. How does it work with Backbone?Thursday, 14 February 13
  18. 18. Backbone.Collection ... _prepareModel: function(model, options) { options || (options = {}); if (!(model instanceof Model)) { var attrs = model; options.collection = this; model = new this.model(attrs, options); if (!model._validate(model.attributes, options)) { model = false; } } else if (!model.collection) { model.collection = this; } return model; }, ...Thursday, 14 February 13
  19. 19. Backbone.Model ... // Create a new model with identical attributes to this one. clone: function() { return new this.constructor(this.attributes); }, ...Thursday, 14 February 13
  20. 20. Caveats Maps take space Logout should clear the map Tests should clear the map Can’t subclass (yet)Thursday, 14 February 13
  21. 21. github.com/shinetechThursday, 14 February 13

×