Introduction to LocalStorage and Store.js

Introduction

Have you used localStorage to store values in the browser persistently? Have you used it to store integer values only to find out that it actually only stores values as strings? In this article I’m going to walk you through a library called store.js which allows you to use the power of localStorage while still giving you the functionality that you expect (eg. Storing values in their original data types).

But before we play with Store.js I’m gonna give you a quick introduction on LocalStorage. LocalStorage allows you to store data locally (in your computer). It’s also a persistent storage which means that the data that you store using LocalStorage will actually stay there even after a power-interruption or you accidentally closed your browser. Here are the things you need to remember when using LocalStorage:

  • It’s data that is stored browser-wide which means that the data is not linked to a single browser tab. If that’s a bit unclear to you try storing a new item in the localStorage, open a new tab and go to google.com. You will still get the item that you have set even if you didn’t set the item on the same tab.
localStorage['name'] = 'kyokasuigetsu'
localStorage['name']; //output: kyokasuigetsu
  • There are two ways you can store localStorage item. The first one is by using the bracket notation, and the second one is the dot notation. Just like how you set or get values for individual properties in a JavaScript object.
localStorage['speed'] = '10,000 miles per hour
localStorage.setItem('speed', '10,000 miles per hour')
  • It can only store string values. To demonstrate this let’s try storing an integer value in localStorage and add a value into it. Go ahead and try it using the console in Chrome developer tools or see the example below. You’ll see that the output is 21 instead of the value that were expecting which is 3. This means that any other data type is converted to string (stringified) when stored in localStorage which isn’t very nice since you have to convert localStorage items to their proper data type in order to make sense out of them.
localStorage.setItem('number', 2)
localStorage.getItem('number') + 1 //output: 21

LocalStorage only stores string values that’s why some cool people creates libraries like store.js to make localStorage awesome.

To use store.js you have to include it on the page where you want to use it.

<script src="store.js></script>

Items in store.js are stored in groups called stores. Here’s how to create a new store. It’s like creating a new object of the Store class.

var items = new Store('items')

You then get to store items inside it:

items.set('number', 2)

We can also get the item that we have just set and add 1 to it. Now you’ll see that the output is 3 which means that the number 2 wasn’t converted to a string value.

items.get('number') + 1 //output: 3

Ok now were done with an example I might as well show you the different data types which you can store using store.js. I have just showed you how to store integer values. Everything is pretty much an object in JavaScript but if you’re fairly new to JavaScript you might call the items that were storing below an array.

items.set('numbers', [1,2,3,4,5])
items.get('numbers') //output: [1, 2, 3, 4, 5]
items.get('numbers')[2] //output: 3
items.get('numbers')[2] + items.get('numbers')[1] //output: 5

We can also store objects. Yeah I know that I just called arrays as objects a few seconds back so don’t take my word for it as I’m not a JavaScript expert.

var people = {
 name: 'kyokasuigetsu',
 role: 'katana',
 ability: 'illusion'
}

We can simply use the name of the object to store them in the items store.

items.set('obj', people)

You can also get the whole object.

items.get('obj')

You’ll get an object tree if you execute the code above.
image

We can also get the values of individual properties that are stored in the objects.

items.get('obj').role //output: "katana"

Mini Project

Ok enough with the basics this time were gonna be building a mini project using localStorage and Store.js. Here’s what our output is going to look like.

image

Yeah I know it’s a bit ugly but I’m trying to keep the styling simple so it won’t get in the way of our main subject which is localStorage and store.js so just bear with me. Just modify the styling to your liking once were done with it. And here’s the demo in case you want to get a feel of it before we build it.

As you can see from the screenshot above our mini project is going to allow us to create 3 characters with name, skills, and items as its attributes. There is a function that will allow us to reset the storage which means deleting the contents of the localStorage. There is also a function that will allow us to delete a single character from our list. Were also going to implement event listeners which allows us to listen for events in the localStorage, this will allow us to do something on any instance of our project on the same browser window. Basically what we want is to automatically update other tabs which is accessing the same page so that if we delete something on one tab, the other tab will also have that change even if we didn’t perform the delete action from that tab.

First let’s define the styling for our mini project.

<style>
#create, .box {
    width: 210px;
    height: 220px;
    padding: 17px;
	border: 2px solid;
	float:left;
}

#characters{
	width: 744px;
	height: 254px;
	border: 2px solid black;
	float:left;
}
</style>

For this mini project I also used jquery to minimize the code that we need to write. So include it on your page as well.

<script src="store.js"></script>
<script src="jquery171.js></script>

Next is the form where the user is going to create a new character.

<div id="create">
	<h2>Create Character</h2>
	<p>
	<label for="name">Name</label>
	<input type="text" id="name"/>
	</p>

	<p>
	<label for="name">Skills</label>
	<input type="text" id="skills"/>
	</p>

	<p>
	<label for="name">Items</label>
	<input type="text" id="items"/>
	</p>

	<p>
	<input type="button" id="btn_create" value="create"/>
	<input type="button" id="btn_reset" value="reset storage"/>
	</p>
</div>

And then the container where we are going to put our characters later on.

<div id="characters"></div>

Initialize the variable where we are going to store the characters temporarily and permanently (until user decides to delete it)

var chars = []; //store characters temporarily
var s_char = new Store('character'); //store characters until you delete it

Next check if there is already a character that was saved in the character store. If there is already a character (1 or more characters) then we loop through the character store and get the character information (name, skills, items) then display them on the container for characters using the put_contents() function.

The put_contents() function which takes up 4 arguments: the id, name, skills, and the items. The variable x stores the index of the character in the character store so we used it as an id.

if(s_char.get('characters')){
	for(var x in s_char.get('characters')){
	   var name = s_char.get('characters')[x]['name'];
	   var skills = s_char.get('characters')[x]['skills'];
	   var items = s_char.get('characters')[x]['items'];

	   put_contents(x, name, skills, items);
	}
}

The put_contents() function is used to append character information into the character container.

function put_contents(id, name, skills, items){
		var div = $("<div>").attr('class', 'box').appendTo('#characters');
		$("<p>").text('Name: ' + name).appendTo(div);
		$("<p>").text('Skills: ' + skills).appendTo(div);
		$("<p>").text('Items: ' + items).appendTo(div);
		$("<p>").html("<input type='button' class='btn_delete' id="+ id +" value='delete'/>").appendTo(div);
	}

Next we listen for the click even on the create character button.

$('#btn_create').click(function(e){
	var character_count = $('.box').length;
	if(character_count < 3){ //we can only add up to 3 characters
		var name	= $('#name').val();
		var skills	= $('#skills').val();
		skills = skills.split(','); //convert skills to array
		var items	= $('#items').val();
		items = items.split(','); //convert to items array

		//create a template for the character
		var character = function(name, skills, items){
		 this.name = name,
		 this.skills = skills,
		 this.items = items
		}

		//create new characters from the template
		chars[character_count] = new character(name, skills, items);

		s_char.set('characters', chars); //save character to store

		put_contents(character_count, name, skills, items);

		$('input[type=text]').val(''); //clear all textbox
	}else{
		alert('Cannot create more than 3 characters');
	}
});

I really got lazy in writing the code for the deletion of a single character. What I did was to empty the whole container for character, create a copy of the current characters in the storage, delete the character from the copy, copy back the contents of the copy into the store, then finally loop through all the characters stored in the store and display them on the character container.

$('.btn_delete').live('click', function(){

	//using delete leaves an undefined item on the index
	//that was deleted the following code
	//removes the undefined items
	$('.box').remove();
	var characters = s_char.get('characters');
	var id = $(this).attr('id');

	delete characters[id];

	var tmpArray = new Array();
	for(el in characters) {
		 if(characters[el]) { //if current item is not a falsy value
			  tmpArray.push(characters[el]);
		 }
	}
	s_char.set('characters', tmpArray);  //save to store

	//loop through the new list of characters
	for(var x in tmpArray){
		var name = tmpArray[x]['name'];
		var skills = tmpArray[x]['skills'];
		var items = tmpArray[x]['items'];

		put_contents(x, name, skills, items);
	}
});

To clear all the characters we just use the reset method in store.js what it does is to remove all the values from a store and then restore the defaults.

$('#btn_reset').click(function(){
	s_char.reset(); //resets the s_char store
	alert('Storage has been successfully reset!');
	$('.box').remove();
});

Lastly we add an event listener to localStorage so that if something happens to it (adding of items, deletion of items, etc.) an event will be executed on other tabs that accesses the same page on the same window.

The code below is pretty simple, it says that when something happens to the localStorage we reload the page. So if we have three tabs open (1 for the 1 that were currently looking at and 2 for the other tabs which is also navigated to the same page) the other 2 tabs will reload if we add, delete or reset the storage. There are a lot of better ways to do this but for the sake of simplicity and laziness here’s what I did so I advise you not to follow this one if you’re doing this for a client or some serious personal project.

window.addEventListener("storage", function(e){
	location.reload();
}, false);

Conclusion

That’s pretty much all I got for this tutorial. You’ve learned how to do things in localStorage and store.js, we also built a mini project utilizing the power of store.js. I hope you enjoyed this tutorial. Please comment if you think its terrible or there’s some information that is missing so that I could improve it. If you know of alternatives to store.js share them in the comments. Thanks!

Resources

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s