Created
October 24, 2012 19:08
-
-
Save gf3/3948171 to your computer and use it in GitHub Desktop.
Backbone Model Instance Sharing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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