I was talking to a colleague recently about the release of McSandy, and he mentioned that he had a project coming up that would require manipulation of HTML5’s LocalStorage API. I pointed him to a small gist that I’d put up on Github. And then I thought, “hey, maybe I should mention this to other folks, too.”
I don’t really have a good name for this. I guess you could just call it store.js because it only really does two things:
- Acts as a wrapper for both localStorage and sessionStorage
- Lets you store and retrieve objects
It’s the latter bullet point that makes this pattern handy. LocalStorage and SessionStorage only store strings! If you want to store objects, you need to stringify and parse things; unless you use something like store.js.
What I’ve done is set a global variable called
Store has four methods:
get(type, key, value)
Watch for the Type
type is the only thing that isn’t totally intuitive, because it’s meant to be one of two integers. Set type to
0 for localStorage, and
1 for sessionStorage.
Also, if you notice, the
get() method is a little odd. That’s because I set it to allow you to retrieve an item by either the key, or its index number. So
get() merge’s LocalStorage’s
store.set(0, 'foo', 'bar') // uses localStorage, sets an item with the key 'foo' and the value 'bar' store.get(0, 'foo') //uses localStorage, returns the value of the key 'foo' store.del(0, 'foo') //deletes the item 'foo' from localStorage store.clr(0) //deletes everything in localStorage
Here’s the Gist. I’ve used this in at least a dozen different projects; it’s managed to hold up so far. Give it a shot and let me know if there’s any opportunity for improvement.