Created
October 16, 2014 14:00
-
-
Save davidbiehl/9c0516c608956726cfb7 to your computer and use it in GitHub Desktop.
Promising Identity Map for Backbone (Draft)
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
App.module "Data", (Data, App, Backbone, Marionette, $, _)-> | |
class Data.IdentityMap | |
constructor: (@collection, opts={})-> | |
@promiseAll = false | |
@promiseEach = {} | |
if opts.fetch == false | |
@promiseAll = $.Deferred() | |
@promiseAll.resolve @collection | |
getAll: -> | |
unless @promiseAll | |
@promiseAll = $.Deferred() | |
@collection.fetch | |
success: @promiseAll.resolve | |
error: @promiseAll.reject | |
@promiseAll.promise() | |
get: (id)-> | |
unless @promiseEach[id] | |
dfd = @promiseEach[id] = $.Deferred() | |
model = @collection.get(id) | |
if model | |
dfd.resolve(model) | |
else | |
new @collection.model(id: id).fetch | |
success: dfd.resolve | |
error: dfd.reject | |
@promiseEach[id].promise().done (model)=> | |
@collection.add(model) | |
model.once "destroy", => | |
delete @promiseEach[id] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment