History

History provides back, forward, and refresh functionality for your JavaScript applications.

Install

Include the history plugin.

include.plugins('history')

Use

The history plugin provides little in the way of an API. It simply detects when the back, forward, or refresh button is called, checks the url, and calls the appropriate action. Learning to use history is really about how to implement it in your controllers and views.

The part of the url that history uses is the url hash.

Url hash

The url's hash is the url text to the right of #. For example:

http://yourdomain.com/my_jmvc_app.html#todos/show&id=1

The url's hash, and the part that history uses, is todos/show&id=1.

Example

Lets say you wanted to create a page listing todos, and a page showing detailed information for individual todos. You want users to have the ability to click back and forth between seeing all the todos and just the one they clicked on.

Here are your todos:

mytodos = [{id: 1, name: 'brush teeth', due: '10/20/08'},
           {id: 2, name: 'sort out recycling', due: '10/21/08'},
           {id: 3, name: 'take off business socks', due: '10/22/08'}]

To do this, you want to create a todos controller with a list and show action.

Controller('todos',{
  list: function(params){
    this.todos = mytodos
    this.render(); // renders app/views/todos/list.ejs
  },
  show: function(params){
    this.todo = mytodos[params.id];
    this.render(); // renders app/views/todos/show.ejs
  }
});

The list and show functions will be called with url hashes like: todos/list and todos/show&id=X respectively. The X is a number corresponding to which todo is going to be shown. Notice how it is accessed in the params in the show action.

Finally, we have to create the views that link to these controller actions.

list.ejs

<h1>Listing Todos</h1>
<table>
  <tr>
    <th>ID</th><th>Name</th>
  </tr>
  <%for(var i = 0 ; i < todos.length; i++){%>
	<%var todo = todos[i]%>
	<tr class='todo'>
		<td><%= todo.id%></td>
		<td><%= todo.name%></td>
		<td><a href='#todos/show&id=<%=todo.id%>Show</a></td>
	</tr>
  <%}%>
</table>

show.ejs

<h1>Showing todo</h1>
<div class='todo'>
	<p><label>Title: </label><%=todo.name%></p>
	<p><label>Due on: </label><%=todo.due%></p>
</div>
<a href='#todos/list'>List todos</a>

Notice the higlighted hyperlinks. These change the url's hash which results in either the todos list or show action being called.