Skip to content

Instantly share code, notes, and snippets.

@therabidbanana
Created August 15, 2012 15:50
Show Gist options
  • Save therabidbanana/3361154 to your computer and use it in GitHub Desktop.
Save therabidbanana/3361154 to your computer and use it in GitHub Desktop.
Identity Map for backbone models

I read this trick on the Soundcloud blog: http://backstage.soundcloud.com/2012/06/building-the-next-soundcloud/

You can return an existing object from a javascript constructor to avoid creating a new object. I'm using this as an identity map - one instance per id. Adapted to Coffeescript and adding a feature to update the existing class with any new information (me.set(data)), it looks something like user.coffee.

You have to copy-paste the simple return super constructor into every child class. Without this the code breaks. Not sure how to solve this issue.

App = {}
data_store = {}
class App.Model extends Backbone.Model
constructor: (data)->
name = this.__proto__.constructor.name
if data?.id? && data_store["#{name}/#{data?.id}"]
me = data_store["#{name}/#{data?.id}"]
me.set(data)
return me
else
super
set: (data)->
name = this.__proto__.constructor.name
ret = super
data_store["#{name}/#{@id}"] ||= @ if @id?
ret
class App.User extends App.Model
constructor: ()-> return super
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment