Identity Maps & BackboneBen Teese, Shine Technologies
Thursday, 14 February 13
Overview
The Problem
About Identity Maps
Backbone.IdentityMap
Thursday, 14 February 13
A Demo
Thursday, 14 February 13
Thursday, 14 February 13
Thursday, 14 February 13
Thursday, 14 February 13
The Problem
Roger
fetch
GET /suspects/1
Backend
fetch
GET /suspects
Collection ...
Todd
Michael
Roger
Thursday, 14 February 13
What we want
Roger
fetch
GET /suspects/1
Backend
fetch
GET /suspects
Collection ...
Todd
Michael
Thursday, 14 February 13
Identity Maps
Thursday, 14 February 13
Identity Map
Todd
Michael
Roger
Fred
Suspect:1
Suspect:2
Suspect:3
Suspect:4
......
Thursday, 14 February 13
Object Creation
if class and ID is in identity map return the cached objectelse create new object put it in identity map return the new objectend
Thursday, 14 February 13
Backbone.IdentityMap
Backbone ‘Plugin’
Overrides Model Constructor
Does not alter original Backbone
Thursday, 14 February 13
Before...
var Suspect = Backbone.Model.extend({ ...}); var Suspects = Backbone.Collection.extend({ model: Suspect, url: "/suspects"});
...
Thursday, 14 February 13
After...
var Suspect = Backbone.IdentityMap( Backbone.Model.extend({ ... })); var Suspects = Backbone.Collection.extend({ model: Suspect, url: "/suspects"});
...
Thursday, 14 February 13
Thursday, 14 February 13
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
How does it work with Backbone?
Thursday, 14 February 13
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
Backbone.Model
...// Create a new model with identical attributes to this one.clone: function() { return new this.constructor(this.attributes);},...
Thursday, 14 February 13
Caveats
Maps take space
Logout should clear the map
Tests should clear the map
Can’t subclass (yet)
Thursday, 14 February 13
github.com/shinetech
Thursday, 14 February 13