Skip to content

Instantly share code, notes, and snippets.

@umeboshi2
Forked from davemo/backbone.sessionStorage.js
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umeboshi2/ba21b925dc388cd91055 to your computer and use it in GitHub Desktop.
Save umeboshi2/ba21b925dc388cd91055 to your computer and use it in GitHub Desktop.
###*
Backbone sessionStorage Adapter
Based on https://github.com/jeromegn/Backbone.localStorage
###
(->
# A simple module to replace `Backbone.sync` with *sessionStorage*-based
# persistence. Models are given GUIDS, and saved into a JSON object. Simple
# as that.
# Hold reference to Underscore.js and Backbone.js in the closure in order
# to make things work even if they are removed from the global namespace
# Generate four random hex digits.
S4 = ->
(((1 + Math.random()) * 0x10000) | 0).toString(16).substring 1
# Generate a pseudo-GUID by concatenating random hexadecimal.
guid = ->
S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()
_ = @_
Backbone = @Backbone
# Our Store is represented by a single JS object in *sessionStorage*. Create it
# with a meaningful name, like the name you'd give a table.
# window.Store is deprectated, use Backbone.SessionStorage instead
Backbone.SessionStorage = window.Store = (name) ->
@name = name
store = @sessionStorage().getItem(@name)
@records = (store and store.split(",")) or []
return
_.extend Backbone.SessionStorage::,
# Save the current state of the **Store** to *sessionStorage*.
save: ->
@sessionStorage().setItem @name, @records.join(",")
return
# Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
# have an id of it's own.
create: (model) ->
unless model.id
model.id = guid()
model.set model.idAttribute, model.id
@sessionStorage().setItem @name + "-" + model.id, JSON.stringify(model)
@records.push model.id.toString()
@save()
model.toJSON()
# Update a model by replacing its copy in `this.data`.
update: (model) ->
@sessionStorage().setItem @name + "-" + model.id, JSON.stringify(model)
@records.push model.id.toString() unless _.include(@records, model.id.toString())
@save()
model.toJSON()
# Retrieve a model from `this.data` by id.
find: (model) ->
stored = @sessionStorage().getItem(@name + "-" + model.id)
if stored
JSON.parse stored
else
null
# Return the array of all models currently in storage.
findAll: ->
_(@records).chain().map((id) ->
JSON.parse @sessionStorage().getItem(@name + "-" + id)
, this).compact().value()
# Delete a model from `this.data`, returning it.
destroy: (model) ->
@sessionStorage().removeItem @name + "-" + model.id
@records = _.reject(@records, (record_id) ->
record_id is model.id.toString()
)
@save()
model
sessionStorage: ->
sessionStorage
# sessionSync delegate to the model or collection's
# *sessionStorage* property, which should be an instance of `Store`.
# window.Store.sync and Backbone.sessionSync is deprectated, use Backbone.SessionStorage.sync instead
Backbone.SessionStorage.sync = (method, model, options, error) ->
store = model.sessionStorage or model.collection.sessionStorage
# Backwards compatibility with Backbone <= 0.3.3
if typeof options is "function"
options =
success: options
error: error
resp = undefined
syncDfd = $.Deferred()
switch method
when "read"
resp = (if model.id? then store.find(model) else store.findAll())
when "create"
resp = store.create(model)
when "update"
resp = store.update(model)
when "delete"
resp = store.destroy(model)
if resp
options.success resp
syncDfd.resolve()
else
options.error "Record not found" if options.error
syncDfd.reject()
syncDfd.promise()
Backbone.SessionStorage.ajaxSync = Backbone.sync
Backbone.sessionStorageEnabled = true
Backbone.bypassSessionStorage = (obj, func, options) ->
Backbone.sessionStorageEnabled = false
result = func.call(obj, options or {})
Backbone.sessionStorageEnabled = true
result
Backbone.getSyncMethod = (model) ->
return Backbone.SessionStorage.sync if (model.sessionStorage or (model.collection and model.collection.sessionStorage)) and Backbone.sessionStorageEnabled
Backbone.SessionStorage.ajaxSync
# Override 'Backbone.sync' to default to localSync,
# the original 'Backbone.sync' is still available in 'Backbone.ajaxSync'
Backbone.sync = (method, model, options, error) ->
Backbone.getSyncMethod(model).apply this, [
method
model
options
error
]
return
)()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment