Created
November 25, 2012 18:56
-
-
Save janroesner/4144796 to your computer and use it in GitHub Desktop.
Backbone Collection Cache
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
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