Skip to content

Instantly share code, notes, and snippets.

@davidbiehl
Created October 16, 2014 14:00
Show Gist options
  • Save davidbiehl/9c0516c608956726cfb7 to your computer and use it in GitHub Desktop.
Save davidbiehl/9c0516c608956726cfb7 to your computer and use it in GitHub Desktop.
Promising Identity Map for Backbone (Draft)
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