Created
August 25, 2011 16:00
-
-
Save oivoodoo/1171026 to your computer and use it in GitHub Desktop.
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
/* | |
* Wrapper for html5 local storage | |
*/ | |
var Storage = function() {}; | |
Storage.define = function(table) { | |
window.localStorage[table] = window.localStorage[table] || "[]"; | |
return new Table(table); | |
}; | |
var Table = function(table, storage) { | |
this.table = table; | |
this.shortName = table.toLowerCase(); | |
}; | |
Table.prototype.isNeedUpdate = function(data) { | |
return this.diff(data).length > 0; | |
}; | |
Table.prototype.save = function(data) { | |
var values = JSON.stringify(this.array(data)); | |
window.localStorage[this.table] = values; | |
}; | |
Table.prototype.load = function() { | |
return JSON.parse(window.localStorage[this.table]); | |
}; | |
Table.prototype.diff = function(data) { | |
var items = _.pluck(this.load(), "id"); | |
var ids = this.array(data); | |
return _.difference(ids, items); | |
}; | |
Table.prototype.value = function(item) { | |
return item[this.shortName]; | |
}; | |
Table.prototype.array = function(items) { | |
return _.reduce(items, function(memo, item) { return memo.concat(this.value(item)); }, [], this); | |
}; | |
Table.prototype.get = function(id) { | |
var items = load(); | |
return _.detect(items, function(item) { item.id == id }); | |
}; | |
window.Storage = Storage; | |
window.Table = Table; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment