Created
October 16, 2012 06:41
-
-
Save netsi1964/3897580 to your computer and use it in GitHub Desktop.
javascript localstorage toDo list
This file contains hidden or 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
/**** | |
Sten Hougaard, @netsi1964, Localstorage items | |
Ver 0.98, not fully tested | |
Please note: Do not support storing of objects with functions | |
Added option to parse key (when using more than one localstorage) | |
Changed names from toDos to items, more generic | |
****/ | |
var items; | |
if (typeof localStorage === 'undefined' ) { | |
alert('Your browser does not support HTML5 localStorage. Try upgrading.'); | |
} else { | |
try { | |
items = { | |
key: 'items'+(new Date()-new Date(1964,8,23)), | |
getItems: function(key) { | |
key = (typeof key!=='undefined') ? key : this.key; | |
var _temp = localStorage.getItem(key); | |
var current = (_temp===null) ? [] : JSON.parse(_temp); | |
localStorage.setItem(key, JSON.stringify(current)); | |
return current; | |
}, | |
add: function(oItem, key) { | |
key = (typeof key!=='undefined') ? key : this.key; | |
var items = this.getItems(key); | |
items[items.length] = JSON.stringify(oItem); | |
return localStorage.setItem(key, JSON.stringify(items)); | |
}, | |
set: function(index, value, key) { | |
key = (typeof key!=='undefined') ? key : this.key; | |
var items = JSON.parse(this.getItems()); | |
items[index] = value; | |
localStorage.setItem(key, JSON.stringify(items)); | |
return items; | |
}, | |
get: function(index, key) { | |
key = (typeof key!=='undefined') ? key : this.key; | |
var items = this.getItems(); | |
return JSON.parse(items[index]); | |
}, | |
remove: function(index, key) { | |
key = (typeof key!=='undefined') ? key : this.key; | |
var items = this.getItems(); | |
var removed = items.splice(index, 1); | |
localStorage.setItem(key, JSON.stringify(items)); | |
return removed; | |
} | |
} | |
} catch (e) { | |
if (e == QUOTA_EXCEEDED_ERR) { | |
alert('Quota exceeded!'); //data wasn’t successfully saved due to quota exceed so throw an error | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment