Skip to content

Instantly share code, notes, and snippets.

@rylan
Created July 29, 2012 15:35
Show Gist options
  • Save rylan/3199535 to your computer and use it in GitHub Desktop.
Save rylan/3199535 to your computer and use it in GitHub Desktop.
Enyo IndexedDB component
/* This is an example of creating an Enyo component for handling calls to an IndexedDB.
* This example is pretty basic, the DB is based around a Road object that has
* a description and location (unique), the location is used as the key for the record.
*
* Tested and works in Chrome, however testing in Firefox seems to fail do not know why.
*/
enyo.kind({
name: "IndexedDBControl",
kind: "Component",
published: {
database: "MyRoads",
version: "1.0",
},
events: {
onLoaded: "",
},
create: function() {
var request,
that = this;
this.db = null;
this.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || windows.msIndexedDB;
if ('webkitIndexedDB' in window) {
window.IDBTransaction = window.webkitIDBTransaction;
window.IDBKeyRange = window.webkitIDBKeyRange;
}
request = this.indexedDB.open(this.database, this.version);
request.onupgradeneeded = function(evt) {
var store = that.db.createObjectStore("road", {keyPath: "src"});
store.createIndex("description", "description", {unique: false});
};
request.onsuccess = function (evt) {
that.db = evt.target.result;
that.doLoaded();
};
request.onfailure = enyo.bind(this, this.openDBFailed);
},
openDBFailed: function(inError) {
console.log("db open error");
},
insertRoad: function(inRoad, callback, errorCallback) {
var that = this,
trans = this.db.transaction("road", IDBTransaction.READ_WRITE),
store = trans.objectStore("road"),
request = store.add({description: inRoad.description, src: inRoad.location});
request.onsuccess = function(evt){
console.log("Added entity");
callback();
}
request.onfailure = function(evt){
errorCallback(evt);
}
},
deleteRoad: function(inRoad, callback, errorCallBack) {
var that = this,
trans = this.db.transaction("road", IDBTransaction.READ_WRITE),
store = trans.objectStore("road"),
request = store.delete(inRoad.src);
request.onsuccess = function(evt){
console.log("Entity Removed");
callback();
}
request.onfailure = function(evt){
errorCallback(evt);
},
getMyAll: function(callback, errorCallback) {
var trans,
store,
entities = [],
cursorRequest;
if(this.db){
trans = this.db.transaction("road", IDBTransaction.READ_WRITE);
store = trans.objectStore("road");
trans.oncomplete = function(evt) {
callback(entities);
};
cursorRequest = store.openCursor();
cursorRequest.onerror = function(error) {
errorCallback(error);
};
cursorRequest.onsuccess = function(evt) {
var cursor = evt.target.result;
if (cursor) {
roads.push(cursor.value);
cursor.continue();
}
};
}
},
});
@rylan
Copy link
Author

rylan commented Jul 30, 2012

Currently not supported in IE10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment