Easy Templating with Mustache.js

Introduction

Any web development dude who is worth their salt would say to you
that you have to separate presentation code from logic code. That’s
why MVC, templating , MVP, MVVM and other acronyms where created.
Why separate presentation and logic?
To make code more maintainable and pleasing to the eyes of the
poor soul whose reading your code. Here’s an example of code that doesn’t use
templating:


var anime = {
	'cool' : [
		'onepiece','k-on','bleach','naruto','hanasaku iroha','star driver','yuru yuri','a channel','tari tari','sword art online','durarara'
	]
};
var parent = $('#no_templates'); //get the element where we are going to append things
var h1 = $('<h1>').text('Without templating'); //create a header
var ul = $('<ul>'); //create a ul element

h1.appendTo(parent); //append header to the no_templates div
ul.appendTo(parent); //append ul to the no_templates div

for(var x in anime.cool){
//append list item into the list
var li = $('<li>').text(anime.cool[x]).appendTo(ul);
}

What the code above does is simply to loop over a list cool anime and append each of them in an onordered list.
Ugly isn’t it?

In this tutorial I’m going to introduce to you a templating library
called Mustache. Mustache is available in
a variety of languages including PHP, Ruby, Python, Clojure, Node.js, ActionScript, and of course
JavaScript which is the flavor that were gonna be using today.

So yeah, go ahead and download Mustache.js from Github then include it into your page. As you might have noticed from the code a moment ago
I also used jQuery to make the code shorter and easier to write. So if you don’t have it yet you can either go to the jQuery site and download your copy or select jQuery 1.7.1 from this site. Later versions might also work.


<script type="text/javascript" src="mustache.js"></script><!--include mustache-->
<script type="text/javascript" src="jquery171.js"></script><!--include jQuery-->

Playing


Basics

To use mustache you must have a data source. This can be an array, a JSON string, a variable. Pretty much these are all objects in JavaScript so I’ll just go ahead and use the term object as a data source for mustache. Another thing that you’re going to need is a template which is basically HTML code where you specify how your data will be rendered in the page. For example if you want something to be displayed as a header the template is where you do it.
Lastly, you’re going to need an HTML element where you want to show your data.
That is all you need when using mustache. A data source , a template, and an HTML element where you want to show your data. Here’s an example:


<script type="text/javascript">
//define an object
var obj = {
		search : 'google',
		sites : ['google', 'twitter', 'facebook']
	};

var template = "<h1>Search Engine:{{search}}</h1>"; //define the template
var html = Mustache.to_html(template, obj); //put the data into the template
$('#container').html(html); //update the container div

</script>
<div id="container"></div>
<pre>

For your template code you just need to place the name of the property that you want to output in a specific tag. In this case the name of the property is search with the value of google. The value is the one that’s going to be rendered inside your template. So the code above will output the word google inside h1 tags.

Next I’m going to show you how to use sections. In programming terms sections are similar to the repeated portion of a loop. In sections we specify a start and an end and the portion that goes between the start and end is the repeated part based on the value of the current item. Here’s how to define a section (were using the same object from earlier):


var template = "<ul>{{#sites}}<li>{{.}}</li>{{/sites}}</ul>"; 

var html = Mustache.to_html(template, obj); //put the data into the template
$('#container').html(html); //update the container div

Let’s break it down. {{#sites}} define the start of the section {{/sites}} define its end. So the pound sign(#) defines the start and the forward-slash(/) defines the end. In between we put some
li tags because they’re basically repeated. Just remember that anything that is supposed to be repeated goes inside the section definition. Lastly we have this weird double mustache with a dot inside ({{.}}) which simply refers to the current item in the list.

Going Deeper


A cleaner way of writing templates

Were done with the basics now let’s try to go deeper. If you think defining templates this way is still ugly you’re not alone I think it’s also ugly. You might have notice that you can’t also go another line when defining templates like we did earlier. You’ll get a nasty error and you need to use plus(+) symbols to append stuff if your template becomes longer than the Golden Gate bridge.


var template = "<ul>{{#sites}}<li>{{.}}</li>{{/sites}}</ul>";

Well good news for you since there’s actually another way of defining a template all you have to do is to place your template inside tags but with the
type of text/html instead of the usual text/javascript which we don’t even need when using html5. Here’s an example:

<script id="anime" type="text/html">
<ul>
	{{#watched}}
	<li>{{.}}</li>
	{{/watched}}
</ul>
</script>

And there’s a bit difference in the code for assigning the data source into the template. Examine the code below:

<script type="text/javascript">
var anime = {
			'watched' : [
						'onepiece','k-on','bleach','naruto',
						'hanasaku iroha','star driver','yuru yuri',
						'a channel','tari tari','sword art online','durarara'
			]
		};

var html = Mustache.to_html($('#anime').html(), anime);
$('#container').html(html);
</script>

<div id="container"></div>

As you might have notice we changed this part of the code to use the template that we have created earlier. All you have to do is to select it using a css selector in this case were selecting the template with the id of anime.

var html = Mustache.to_html($('#anime').html(), anime);


A different structure for data source

Were fine with how the data source is structured so far. But what if our data source is structured in a different way? In some cases we have to deal with data coming from other websites like twitter or facebook for displaying tweets or status updates from users. Data is not always structured the way we like it. In this part I’ll try to walk you through some of ways in which data can be structured and show you how to place them in our mustache templates.
As you can see from the code below we have some repeated properties in our object. This will affect the way on how we will access them on our template later on.

<script type="text/javascript">
var ind = {
	'people' : [
		{'name' : 'kyoya', 'age' : 20, 'dialect' : 'kansai'},
		{'name' : 'pedro', 'age' : 30, 'dialect' : 'tagalog'},
		{'name' : 'juan', 'age' : 15, 'dialect' : 'pangalatok'}
	],
	'languages' : [
		{'name' : 'php', 'author' : 'rasmus lerdorf'},
		{'name' : 'python', 'author' : 'guido van rosum'},
		{'name' : 'ruby', 'author' : 'yukihiro matsumoto'}
	]
};

	var html = Mustache.to_html($('#languages').html(), ind);
	$('#container').html(html);
</script>
<div id="container"></div>

Here’s the code for the template. For our data there are some repeated items namely the name, dialect, and the author. All we have to do is to place those repeated items inside of the section. If you remember when looping through an array we placed a period {{.}} this time we place the actual name of the item inside the section.

<script id="languages" type="text/html">

<h1>People</h1>

<ul>
	{{#people}}
	<li>
	Name: {{name}} 
	Age: {{age}}
	</li>
	{{/people}}</ul>
	
<hr/>
<h1>Languages</h1>

<ul>
	{{#languages}}
	<li>
	Name: {{name}} 
	Author: {{author}}
	</li>
	{{/languages}}
</ul>
</script>

There are also times when the data source is 3 or more properties deep such as this one:

<script type="text/javascript">
	var characters = {
		deep : {
			'DragonBall' : {
				'Characters' : ['goku', 'gohan', 'trunks', 'cell', 'vegeta'],
				'Techniques' : ['kame hame wave', 'instant transmission']
			},
			'Onepiece' : {
				'Characters' : ['luffy', 'ace', 'zoro', 'nami', 'usopp', 'sanji', 'franky', 'robin', 'brook'],
				'Techniques' : ['Diable Jambe', 'haki', 'hocho sabaki', 'fleur', 'asura']
			}
		}
	};

	var html = Mustache.to_html($('#characters').html(), characters);
	$('#container').html(html);
</script></pre>
<div id="container"></div>
<pre>

If that’s the case all you have to do is to use dot notation to access the properties that you want. Unfortunately bracket notation doesn’t seem to be working on Mustache so better stick with a naming convention that works with dot notation. Check out the JavaScript best practices from the JavaScript toolbox if you want to learn about names that works with dot notation. I’ve also linked to it in the resources section in case you’re far-sighted. Here’s how we access those properties from our template:

<script id="characters" type="text/html">

<h1>Onepiece Characters</h1>

<ul>
	{{#deep.Onepiece.Characters}}
	<li>{{.}}</li>
	{{/deep.Onepiece.Characters}}
</ul>

<h1>Onepiece Techniques</h1>
<ul>
	{{#deep.Onepiece.Techniques}}
	<li>{{.}}</li>
	{{/deep.Onepiece.Techniques}}
</ul>

</script>

Lastly I’m going to show you an example on how to use data from a remote source (let’s just pretend that its from a remote source) and use that data for our mustache templates. For this example were going to use PHP for the backend and some AJAX methods from jQuery (though it should be AJAJ- Asynchrounous JavaScript and JSON since were using JSON not XML, but yeah AJAX sounds nicer) to fetch the data from PHP.

First we’ll have to create a new PHP file (data.php) and then build the data using arrays. JavaScript flavored arrays to be exact. I’m using PHP 5.4 which is the latest version of PHP at the time of writing of this article. It’s always a good idea to use the latest version of a library, a framework or a programming language since there are lots of new features and benefits. More information about what’s new in PHP 5.4. Here are the contents of the php file that serves as our data source. As you can see were just using arrays and then convert it to JSON string using the json_encode() method in php. This is an important step since its easier to make use of JSON in JavaScript.

<?php $data = ['ninjas'=>[
			'naruto'=>['name'=>'naruto', 'skills'=>['rasengan', 'kage bunshin']],
			'sasuke'=>['name'=>'sasuke', 'skills'=>['chidori', 'sharingan']],
			'lee'=>['name'=>'lee', 'skills'=>['leaf hurricane', '5 gates']]
		]
		];

echo json_encode($data); //convert array to JSON string
?>

And we just fetch the data using the $.post method in jQuery. A quick and nice method for doing AJAX request in jQuery. It’s actually a convenience method for the $.ajax method to make life easier for our fingers that are tired from everyday coding.

<script type="text/javascript">
$.post('data.php', {}, function(data){
		var ninja = JSON.parse(data); //parse JSON string from PHP to convert it to an object
		var html = Mustache.to_html($('#ninja').html(), ninja);
		$('#content').html(html);
	});
</script>

<div id="content"></div>

And for the template we use the dot notation again to access the skills of each ninja. Remember to start with the root property which is ninjas:

<script id="ninja" type="text/html">
<h1>Naruto</h1>
<ul>
	{{#ninjas.naruto.skills}}
	<li>{{.}}</li>
	{{/ninjas.naruto.skills}}
</ul>

<h1>Sasuke</h1>

<ul>
	{{#ninjas.sasuke.skills}}
	<li>{{.}}</li>
	{{/ninjas.sasuke.skills}}
</ul>

<h1>Rock Lee</h1>

<ul>
	{{#ninjas.lee.skills}}
	<li>{{.}}</li>
	{{/ninjas.lee.skills}}
</ul>

</script>

Conclusion

So yeah I guess that’s it for this tutorial on how to use Mustache for templating. You’ve learned the basics of Mustache, how to access properties using the dot notation, using JSON data as a data source for your templates. I hope you learned something and please share this tutorial if you like it.

Resources

Playing with Sugar.js

Introduction

Did you ever need the functionality to get the first 2 items in a JavaScript array? Or get the average of all the items? Or maybe sort the items in the array by its length? Or functions for determining if a string has Japanese or Greek characters? Or maybe formatting dates into their string versions? Or getting the exact date from today after 5 months?
Did you ever wish for JavaScript to have these functions built-in to it and that you could easily call it without having to create your own functions?

Now you can have all of these functions by using a library called Sugar.js. It’s sort of like Underscore.js that serves as a utility belt for JavaScript. Most of the functions that you wished JavaScript have for manipulating Strings, Arrays, Dates, and Objects is already included in Sugar.js.

In this article I’ll be giving you an introduction on Sugar.js, what sort of things you can do with it, the functions that you can use for manipulating Strings, Arrays and Objects. I’ll also show you how to write the equivalent of those Sugar.js functions in plain JavaScript function and extending the JavaScript Prototype.
So yeah, let’s get started and play with it. I’ve already linked each of the functions to a fiddle so that you can play with it. I didn’t have any luck including fiddles for the Sugar.js scripts so you might as well play on the Sugar.js site. You can actually edit the sample scripts and see the output right away.

Arrays

Getting a specified number of items from an array starting from index 0.

Sugar.js:

[4, 5, 6, 7].first(2) //output: [4, 5]

Plain JavaScript Function:

function get_first(array, num){
   var new_array = [];

   for(var x = 0; x<num; x++){
      new_array[x] = array[x];
   }
   return new_array;
}
//call: get_first([4,5,6,7], 2)
//output: [4,5]

Extending Array Prototype:

Array.prototype.get_first = function(num){
   var new_array = [];

   for(var x = 0; x<num; x++){
      new_array[x] = this[x];
   }
   return new_array;
}
//call: [1,2,3].get_first(2)
//output: [1,2]

There’s also a function for getting the average from the specified array.
Sugar.js:

   [1,2,3].average(); //output: 2

Plain JavaScript Function:

function get_average(array){
   var r_length = array.length;
   var total = 0;
   for(var x in array){
      total = total + array[x];
   }
   return parseFloat(total) / parseFloat(r_length);
}
//call: get_average([1,2,3]);
//output: 2

Extending Array Prototype:

Array.prototype.get_average = function(){
   var r_length = this.length;
   var total = 0;
   for(var x in this){
      total = total + this[x];
   }
   return parseFloat(total) / parseFloat(r_length);
}
//call: [1,2,3].get_average()
//output: 2

There’s also a function for getting the max and min values from an array.
Sugar.js:

[4, 5, 6].max() //output: 6
[10, 2, 22].min() //output: 2

Plain JavaScript Function:

function sort(array, sortby){
   if(sortby == 'ASC'){
      var val = array.sort(function(a, b){
         return b + a;
                })[0]
   }else if(sortby == 'DESC'){
      var val = array.sort(function(a, b){
         return b - a;
                })[0]
   }
   return val;
}
//call: sort([4,5,22,33,1], 'ASC')
//output: 1
//call: sort([4,5,22,33,1], 'DESC')
//output: 33

Extending Array Prototype:

Array.prototype.max = function(){
   return this.sort(function(a, b){
      return b - a;
                   })[0]
}
//call: [44,50,24,16].max()
//output: 50

 

Array.prototype.min = function(){
   return this.sort(function(a, b){
   return b + a;
                    })[0]
}
//call: [50,2,1,3,16].min()
//output: 1

Numbers

There are also functions used for manipulating numbers. Remember that numbers are delicate so don’t call functions for numbers like the way you do when calling string functions or else you’ll really get a nasty error. If you don’t know what I mean try executing a Sugar.js function normally:

6.isEven() //output: SyntaxError: Unexpected token ILLEGAL

Here’s what you can do to avoid getting errors the first method is by enclosing your number in parentheses and then call the function as you normally would:

(4).isEven() //output: true

Second method is by using bracket notation:

4['isEven']() //output: true

Plain JavaScript Function:

function even(num){
   return num % 2 === 0;
}
//call: even(4)
//output: true

 

function odd(num){
   return num % 2 !== 0;
}
//call: odd(4)
//output: false

Extending the Number Prototype:

Number.prototype.even = function(){
   return this % 2 === 0;
}
//call: 30['even']()
//output: true

 

Number.prototype.odd = function(){
return this % 2 !== 0;
}
//call: 30['odd']()
//output: false

Strings

There are also string functions used for manipulating string. Most of the functions that is included in Sugar.js are already present in plain JavaScript so I won’t use them as examples.

The first function is used for getting a part of a string from the specified index. Remember that programming languages are zero-indexed so you will need to use 0 if you want to get the 1st character, 1 if you want to get the 2nd character and so on.

Sugar.js

'super_duper_cool'.from(12) //output: cool

<strong><span style=”font-size: small;”>Plain JavaScript Function:</span></strong>

function from(str, frm){
   var last = str.length;
   return str.substr(frm, last);
}
//call: from("javascriptiscool", 12)
//output: cool

Extending the String Prototype:

String.prototype.start_from = function(frm){
   var last = this.length;
   return this.substr(frm, last);
}
//call: "youareawesome".start_from(3)
//out: areawesome

Conclusion

Sugar.js is a really nice way to extend the functions that are already built in to JavaScript. If you’re looking for a quick and dirty solution for your JavaScript problems Sugar.js is a way to go. It’s also useful if you want to save time in writing functions from scratch. But if you’re still a JavaScript beginner just like me I would recommend that you go ahead and check out the functions in Sugar.js or Underscore.js and see if you can build those functions from scratch just like what I did here. You could learn a lot in writing JavaScript code by simply doing that.

Resources

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

Useful sites for freelancers looking for online jobs

Whether you’re a currently unemployed professional looking for online jobs or an employee of a certain company looking for things to do on your free time here are some useful sites that will help you find online jobs.

 

WorkFu

A new startup that lets you find jobs both local and telecommute. If you believe you’re pretty competent in your field then this is the site to be. Because you will mostly find jobs at the expert level here. Really useful if you have lots of superpowers.

image

 

Staff

A unique site where you can find jobs that fits the skill that you have included in your profile. It’s unique in the sense that you’re not the one that’s going to look for jobs it’s the site that’s going to send jobs that you might be interested in applying for based on your skills. For example you have included JavaScript, PHP, MySQL as your skill. You will receive emails and text messages (if you have included your cellphone number) on jobs that matches your skills. I believe this is really pretty awesome.

image

 

oDesk

A pretty old one but still useful. Here you get to propose for the price that you want if you think their budget is too low. You can also upload your resume and compose your cover letter or application letter. A really pretty normal jobs site but since it was founded in the year 2003 its already given that it has the most job postings so its  pretty populated with jobs which makes it a bit hard to find the jobs that you’re really interested in.

image

 

LinkedIn

The number one professional networking site where you get to connect with professionals in your field. But it doesn’t end there because you can actually join groups like CodeIgniter developer group, web developer/ web design groups. And you can find relevant job posting on the group. For example if you joined a web developer group you will only find job postings that are related to web development (html, css, javascript, etc.)image

 

Craigslist

You might have heard of this site already but not aware that you can actually post and look for jobs. There’s always a new job posting everyday and if you’re lucky most of them are also online or telecommute jobs. What’s good about this site is that you won’t see how many people applied for the job that you’re trying to apply for. In my opinion this is very useful and it will make you feel like you’re the only person applying for the job which gives you the confidence that you have better chance.

image

 

Freelancer

You might already know this one since it comes close to the word Freelance. Really useful if you already belong to a company because this site is mostly populated by companies looking for online jobs. So if you’re an individual freelancer you might only have luck if you’re really awesome and possess superpowers. One useful feature of this site is the email notifications on the jobs or projects that matches your skills.

image

 

Elance

Similar to freelancer.com because you also have to write proposals which is much like an application letter. Jobs can either be fixed rate or per hour. But before you can look for jobs you have to pass an online test which is really easy since its an open book test. After that you can take something like a certification exam to prove that you’re actually competent in the skills that you included in your profile. This is optional but you get better chances of getting hired for the job if you pass these exams.

image

 

GetACoder

As the name of the site suggests this is a site specifically dedicated to coding. You will most likely find jobs like website design, website development, usability testing, and search engine optimization. Most of the jobs here are project-based.

image

 

ScriptLance

A site where you can find jobs on programming, design, writing and marketing. Most of the jobs here are per project.

image

 

That’s the end of this list. If you know of other useful sites for finding online jobs then talk to me in the comments. Thanks!