Skip to content

Instantly share code, notes, and snippets.

@janroesner
Created November 25, 2012 18:56
Show Gist options
  • Save janroesner/4144796 to your computer and use it in GitHub Desktop.
Save janroesner/4144796 to your computer and use it in GitHub Desktop.
Backbone Collection Cache
define [], ()->
CollectionCache = ->
cache = {}
# returns true if the cache has the given key already
cacheHasKey = (key)->
cache.hasOwnProperty key
# generates a unique key from given arguments
genKey = (args)->
MD5(JSON.stringify(args))
# creates an instance, caches it, and returns the instance
# the trick here is how the instance is created with a dynamic set of arguments
set = (klass, args, key)->
F = (args)->
return klass.apply(@, args)
F.prototype = klass.prototype
instance = new F(args)
cache[key] = instance
# returns a collection instance and caches it if needed
get: ()->
klass = Array::shift.call arguments
key = genKey arguments
if cacheHasKey(key)
cache[key]
else
set klass, arguments, key
CollectionCache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment