10. Identity Map
Suspect:1 Roger
Suspect:2 Todd
Suspect:3 Michael
Suspect:4 Fred
... ...
Thursday, 14 February 13
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
end
Thursday, 14 February 13
12. Backbone.IdentityMap
Backbone ‘Plugin’
Overrides Model Constructor
Does not alter original Backbone
Thursday, 14 February 13
13. Before
...
var Suspect = Backbone.Model.extend({
...
});
var Suspects = Backbone.Collection.extend({
model: Suspect,
url: "/suspects"
});
...
Thursday, 14 February 13
14. After
...
var Suspect = Backbone.IdentityMap(
Backbone.Model.extend({
...
})
);
var Suspects = Backbone.Collection.extend({
model: Suspect,
url: "/suspects"
});
...
Thursday, 14 February 13
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. How does it work
with Backbone?
Thursday, 14 February 13
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. 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. Caveats
Maps take space
Logout should clear the map
Tests should clear the map
Can’t subclass (yet)
Thursday, 14 February 13