Created
September 27, 2011 21:26
-
-
Save Olical/1246292 to your computer and use it in GitHub Desktop.
PersistantObject - A class for working with objects and localStorage. From this post: http://olivercaldwell.co.uk/?p=89
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
| /** | |
| * A persistant object class using localStorage | |
| * | |
| * Copyright Oliver Caldwell 2011 (olivercaldwell.co.uk) | |
| * http://olivercaldwell.co.uk/?p=89 | |
| */ | |
| function PersistantObject(key) { | |
| // Store the key | |
| this.setKey(key); | |
| // Initialise the data as an empty object | |
| this.data = {}; | |
| // Load the data | |
| this.load(); | |
| } | |
| /** | |
| * Sets the key for the instance | |
| * | |
| * @param {String} key Name to set the key to | |
| */ | |
| PersistantObject.prototype.setKey = function(key) { | |
| this.key = key; | |
| }; | |
| /** | |
| * Loads the JSON from localStorage from the key and decodes it | |
| */ | |
| PersistantObject.prototype.load = function() { | |
| // Load the value | |
| var value = localStorage.getItem(this.key); | |
| // If it exists then decode it and store the result | |
| if(value) { | |
| this.data = JSON.parse(value); | |
| } | |
| }; | |
| /** | |
| * Deletes the value from localStorage | |
| */ | |
| PersistantObject.prototype.erase = function() { | |
| // Delete the value | |
| localStorage.removeItem(this.key); | |
| }; | |
| /** | |
| * Save the object back into localStorage | |
| */ | |
| PersistantObject.prototype.save = function() { | |
| // Save the JSON encoded value | |
| localStorage.setItem(this.key, JSON.stringify(this.data)); | |
| }; |
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
| /** | |
| * A persistant object class using localStorage | |
| * | |
| * Copyright Oliver Caldwell 2011 (olivercaldwell.co.uk) | |
| * http://olivercaldwell.co.uk/?p=89 | |
| */ | |
| function PersistantObject(a){this.setKey(a);this.data={};this.load()}PersistantObject.prototype.setKey=function(a){this.key=a};PersistantObject.prototype.load=function(){var a=localStorage.getItem(this.key);if(a)this.data=JSON.parse(a)};PersistantObject.prototype.erase=function(){localStorage.removeItem(this.key)};PersistantObject.prototype.save=function(){localStorage.setItem(this.key,JSON.stringify(this.data))}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment