Skip to content

Instantly share code, notes, and snippets.

@nat-n
Created December 8, 2011 21:54
Show Gist options
  • Save nat-n/1448794 to your computer and use it in GitHub Desktop.
Save nat-n/1448794 to your computer and use it in GitHub Desktop.
A JaxGL Helper used by gist:1448410 to load and display a model from ajax and/or indexedDB
Jax.getGlobal().AsyncHelper = Jax.Helper.create
load_from_idb: (idb_name, os_name, key, onsuccess, onfailure) ->
indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB
IDBTransaction = IDBTransaction || window.webkitIDBTransaction
IDBKeyRange = IDBKeyRange || window.webkitIDBKeyRange
idb_request = indexedDB.open @indexedDB
idb_request.onsuccess = (e) =>
idb = e.target.result
if idb.objectStoreNames.contains @objectStore
active_store = idb.transaction([@objectStore], IDBTransaction.READ_WRITE).objectStore(@objectStore)
get_request = active_store.get @key
get_request.onsuccess = (e) =>
if e.target.result
onsuccess e.target.result.model_data
else onfailure
get_request.onerror = (e) ->
console.log "ERROR: Unable to retrieve data"
onfailure
else onfailure
idb_request.onerror = (e) ->
console.log "ERROR: Unable to open indexedDB"
onfailure
save_to_idb: (idb, v, os, key, data) ->
# idb is a database
# os is the name of an objectstore which will be created if it doesn't exist
if idb.objectStoreNames.contains os
active_store = idb.transaction([os], IDBTransaction.READ_WRITE).objectStore(os)
put_request = active_store.put { key: key, model_data: data }
put_request.onsuccess = (e) -> console.log "Data stored in indexedDB"
put_request.error = (e) -> console.log "Error putting data"; console.log e
else
version_request = idb.setVersion v
version_request.onsuccess = (e) =>
active_store = idb.createObjectStore os, { keyPath: "key" }
put_request = active_store.put { key: key, model_data: data }
put_request.onsuccess = (e) -> console.log "Data stored in indexedDB"
put_request.error = (e) -> console.log "Error putting data"; console.log e
version_request.onblocked = (e) -> console.log "Blocked setting version"; console.log e
version_request.onerror = (e) -> console.log "Error setting version"; console.log e
version_request.onfailure = (e) -> console.log "Failure setting version"; console.log e
load_json: (json_path, callback) ->
xhr = new XMLHttpRequest
xhr.onreadystatechange = =>
if xhr.readyState == 4 # request complete
if xhr.status == 200 # request successful
loaded_data = JSON.parse xhr.responseText
callback loaded_data
else # request erred
throw new Error "XHR error: "+xhr.status+" for "+json_path
xhr.open 'get', json_path, true
xhr.send null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment