Skip to content

Instantly share code, notes, and snippets.

@foca
Created January 18, 2012 22:39
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foca/1636276 to your computer and use it in GitHub Desktop.
Save foca/1636276 to your computer and use it in GitHub Desktop.
Small implementation of Singletons for Backbone
# Public: generates a mixable singleton implementation dependent on a model key.
# Once you mix it into a model, your model gains an .instance method that will
# generate an object and cache it. Further calls to the .instance methods will
# return the same object.
#
# key - The name of the attribute we use to index instances. Defaults to "id".
#
# Example
#
# # Called without arguments uses the "id" as key.
# class Foo extends Backbone.Model
# _.extend this, Singleton()
#
# first_instance = Foo.instance(id: 1)
# second_instance = Foo.instance(id: 1)
#
# first_instance.cid == second_instance.cid
#
# Example
#
# # You can also provide a custom key:
# class Foo extends Backbone.Model
# _.extend this, Singleton("name")
#
# first_instance = Foo.instance(id: 1, name: "Bar")
# second_instance = Foo.instance(id: 2, name: "Bar")
#
# first_instance.cid == second_instance.cid
#
# Example
#
# # You can tell your collections to use singletons by wrapping the
# # constructor:
# class Foo extends Backbone.Model
# _.extend this, Singleton()
#
# class Foos extends Backbone.Collection
# model: (attrs) -> Foo.instance(attrs)
#
# collection = new Foos([{ id: 1 }, { id: 2 }, { id: 3 }])
# object = Foo.instance(id: 1)
# object.cid == collection.first().cid
#
# Returns an object you can mix into object definitions.
@Singleton = (key = "id") ->
{
_instances: {}
instance: (attrs) ->
unless attrs[key] of @_instances
@_instances[attrs[key]] = new this(attrs)
@_instances[attrs[key]]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment