Skip to content

Instantly share code, notes, and snippets.

@gf3
Created October 24, 2012 19:08
Show Gist options
  • Save gf3/3948171 to your computer and use it in GitHub Desktop.
Save gf3/3948171 to your computer and use it in GitHub Desktop.
Backbone Model Instance Sharing
@instance_store = {}
class App.Model extends Backbone.Model
cache_enabled: false
cache_key: "id"
constructor: (attr) ->
@on "destroy", @_removeFromStore
return super unless attr?.id
id = attr.id
klass = @_getJsonRoot()
instance_store[klass] ||= {}
return(
if instance_store[klass][id]
instance_store[klass][id]
else
super
instance_store[klass][id] = this)
_getJsonRoot: ->
@jsonRoot ||= @constructor.toString().match(/^function ([\w]+)/i)[1].toLowerCase()
#--------------------------------------------
# INSTANCE STORE
#--------------------------------------------
_removeFromStore: =>
klass = @_getJsonRoot()
delete instance_store[klass]?[@id]
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment