3 ms·
Neat little implementation. A couple quick thoughts: * Identity maps aren't a panacea -- If you're just getting started, and you don't yet know that you "want"
by jashkenas 14y ago
Neat little implementation. A couple quick thoughts:
* Identity maps aren't a panacea -- If you're just getting started, and you don't yet know that you "want" an identity map, you don't necessarily need one. There are a bunch of situations where having the ability to model multiple versions of the same resource is useful. For example, an "editing" version of the resource with changes that may or may not be applied to the canonical version ... or a "conflict" version of the resource that has been changed on the server, that you can reconcile with the local version.
* Backbone Collections already maintain a map of id-to-model information for you, and you can rely on them as an identity map ... if you don't use "new". Instead, something like this:
Backbone.Collection.prototype.lookup = function(id) {
return this.get(id) || new this.model({id: id});
};
// Then later, instead of `new` or `get`:
Accounts.lookup(id);
... would provide a simple implementation of the same behavior, without having to change the semantics of "new", or maintain an external id-to-object mapping that makes it harder for garbage collection to work later.
There's also a version of the above function that you can add that does "lookup or fetch from the server" -- another alternative is "lookup locally, fetch from the server, or create on the server". Whatever you need for your app.