This project has moved. 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:

Knockoutjs_jHash_SinglePageAppExample.zip

JavaScript

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 + '/' + mail.id); };
      
    // Client-side routes
    jHash.route('{folder}/{mailId}', function() {
        self.chosenFolderId(this.folder);
        self.chosenFolderData(null);
        $.getJSON('data/' + this.mailId + '.json', null, self.chosenMailData);
    });
            
    jHash.route('{folder}', function() {
        self.chosenFolderId(this.folder);
        self.chosenMailData(null);
        $.getJSON("data/" + this.folder + '.json', null, self.chosenFolderData);
    });
         
    // Default Route when page loads without any route specified
    jHash.defaultRoute("Inbox");
};

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

HTML

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

<!-- Mails grid -->
<table class="mails" data-bind="with: chosenFolderData">
        <thead><tr><th>From</th><th>To</th><th>Subject</th><th>Date</th></tr></thead>
    <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>
        </tr>     
    </tbody>
</table>

<!-- 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>
    </div>
    <p class="message" data-bind="html: messageContent" />
</div>

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

Comments

No comments yet.