Abstracts out ModelCache.
authordsc <dsc@wikimedia.org>
Mon, 16 Apr 2012 20:06:10 +0000 (13:06 -0700)
committerdsc <dsc@wikimedia.org>
Mon, 16 Apr 2012 20:07:18 +0000 (13:07 -0700)
lib/base/index.co
lib/base/model-cache.co [new file with mode: 0644]
lib/util/backbone.co

index eb20dbb..b3b17f8 100644 (file)
@@ -1,5 +1,6 @@
 mixins    = require 'kraken/base/base-mixin'
 models    = require 'kraken/base/base-model'
 views     = require 'kraken/base/base-view'
+cache     = require 'kraken/base/model-cache'
 cascading = require 'kraken/base/cascading-model'
-exports import mixins import models import views import cascading
+exports import mixins import models import views import cache import cascading
diff --git a/lib/base/model-cache.co b/lib/base/model-cache.co
new file mode 100644 (file)
index 0000000..5bd459d
--- /dev/null
@@ -0,0 +1,40 @@
+
+function ModelCache (ModelClass, ModelListClass)
+    ModelClass import do
+        CACHE : new ModelListClass
+        ready : false
+        
+        register: (model) ->
+            # console.log "ModelCache(#{@CACHE}).register(#{model.id or model.get('id')})", model
+            if @CACHE.contains model
+                @CACHE.remove model, {+silent}
+            @CACHE.add model
+            model
+        
+        get: (id) ->
+            @CACHE.get id
+        
+        lookup: (id, cb, cxt=this) ->
+            # console.log "ModelCache(#{@CACHE}).lookup(#id, #{typeof cb})"
+            unless @ready
+                @on 'cache-ready', ~>
+                    @off 'cache-ready', arguments.callee
+                    @lookup id, cb, cxt
+                return
+            
+            if @CACHE.get id
+                cb.call cxt, null, that
+            else
+                Cls = this
+                @register new Cls {id}
+                    .on 'ready', -> cb.call cxt, null, it
+            this
+    
+    # Bind the ModelCache methods to the class
+    for m of <[ register get lookup ]>
+        ModelClass[m] .= bind ModelClass
+    
+    ModelClass
+
+
+module.exports = exports = ModelCache
index 4ecfb14..58f2688 100644 (file)
@@ -12,6 +12,14 @@ window?.Backbone = Backbone
 Backbone.setDomLibrary that if window? and (window.jQuery or window.Zepto or window.ender)
 
 
+_bb_events =
+    once: (events, callback, context) ->
+        fn = ~>
+            @off events, arguments.callee, this
+            callback.apply (context or this), arguments
+        @on events, fn, this
+        fn
+
 
 
 /**
@@ -89,7 +97,9 @@ _methodized = exports._methodized = _.reduce do
         o
     {}
 
+
+_.extend Backbone.Events, _bb_events
 for Cls of Backbone.<[ Model Collection View ]>
-    Cls     import _methodized
-    Cls::   import _methodized
+    Cls     import _methodized import _bb_events import Backbone.Events
+    Cls::   import _methodized import _bb_events