This project has moved and is read-only. For the latest updates, please go here.

Using jHash and Knockout.js for Single Page App

Email Sample

This code sample demonstrates using jHash and Knockout.js together to build a simple Email UI. This example was created by modifying the Knockout.js Single Page Application Tutorial to use jHash for the routing.

Download the source code and run the example locally, or check out the code below.

Download Source Code:


function WebmailViewModel() {
    // Data
    var self = this;
    self.folders = ['Inbox', 'Archive', 'Sent', 'Spam'];
    self.chosenFolderId = ko.observable();
    self.chosenFolderData = ko.observable();
    self.chosenMailData = ko.observable();

    // Behaviours    
    self.goToFolder = function (folder) { jHash.root(folder); };
    self.goToMail = function (mail) { jHash.root(mail.folder + '/' +; };
    // Client-side routes
    jHash.route('{folder}/{mailId}', function() {
        $.getJSON('data/' + this.mailId + '.json', null, self.chosenMailData);
    jHash.route('{folder}', function() {
        $.getJSON("data/" + this.folder + '.json', null, self.chosenFolderData);
    // Default Route when page loads without any route specified

ko.applyBindings(new WebmailViewModel());
// Process the "route" on initial page load


<!-- Folders -->
<ul class="folders" data-bind="foreach: folders">
    <li data-bind="text: $data, 
                   css: { selected: $data == $root.chosenFolderId() },
                   click: $root.goToFolder"></li>

<!-- Mails grid -->
<table class="mails" data-bind="with: chosenFolderData">
    <tbody data-bind="foreach: mails">
        <tr data-bind="click: $root.goToMail">
            <td data-bind="text: from"></td>
            <td data-bind="text: to"></td>
            <td data-bind="text: subject"></td>
            <td data-bind="text: date"></td>

<!-- Chosen mail -->
<div class="viewMail" data-bind="with: chosenMailData">
    <div class="mailInfo">
        <h1 data-bind="text: subject"></h1>
        <p><label>From</label>: <span data-bind="text: from"></span></p>
        <p><label>To</label>: <span data-bind="text: to"></span></p>
        <p><label>Date</label>: <span data-bind="text: date"></span></p>
    <p class="message" data-bind="html: messageContent" />

Last edited May 4, 2012 at 3:02 PM by crpietschmann, version 8


No comments yet.