Skip to content

Instantly share code, notes, and snippets.

@shesek
Last active December 10, 2015 04:48
Show Gist options
  • Save shesek/4383554 to your computer and use it in GitHub Desktop.
Save shesek/4383554 to your computer and use it in GitHub Desktop.
setPrototype = Object.setPrototypeOf or (child, parent) -> child.__proto__ = parent
inherit = (parent, child) -> setPrototype child, parent; child.prototype=parent.prototype; child
IdentityMap = (realConstructor) ->
cache = {}
id = realConstructor::idAttribute
inherit realConstructor, (attributes, options) ->
create = -> new realConstructor attributes, options
if objectId = attributes?[id]
if (object = cache[objectId])?
object.set (options?.parse? attributes) or attributes
else cache[objectId] = create()
else
create().once 'change:' + id, (model, objectId) -> cache[objectId] = model
# Usage
SomeClass = IdentityMap class extends Backbone.Model
validate: -> # ...
# ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment