Dugan Chen's Homepage

Various Things

View Templates

After reading my last post, you now have a system that dispatches controller functions based on the URL hash fragment. It works exactly like django’s url dispatcher, only it works with the hash fragment and not the URL. Well, what do you do in the controller functions that you dispatch? In django, the controller usually loads a view.

The easiest way to load views is to first write them as Closure templates. These templates compile to Javascript functions that return HTML code. You can use the output of these functions to create DOM elements.

The following template, for example, creates two javascript function called views.mainView() and views.otherView():

{namespace views}

/**
 * The main view.
 */
{template .mainView}
  <p id="b">Paragraph 1</p>
  <p>Paragraph 2</p>
{/template}

/**
 * The other view.
 */
{template .otherView}
  <p id="b">Paragraph 3</p>
  <p>Paragraph 4</p>
{/template}

You compile it to a Javascript file called views.js. You load views.js. Then you can use these two functions with the URL dispatcher:

/*global $ , createHashHandler, views */

$(function () {
    var handleHashChange = createHashHandler([{
        re: /a/,
        controller: function () {
            $('#mainDiv').html(views.mainView());
        }
    }, {
        re: /b/,
        controller: function () {
            $('#mainDiv').html(views.otherView());
        }
    }]);

    $(window).bind('hashchange', handleHashChange);
    handleHashChange();
});

Now, setting your URL fragment to ‘#a’ will set the contents of your main div to the main view. Setting the URL fragment to ‘#b’ automatically sets the main div’s contents to the other view.

And that, combining Closure templates and my dispatcher, is all you need to structure a single-page web application. Put them together, and you have a Javascript version of Django’s template (view) and view (controller) layers. Your single-page applications can now be as well structured as your multi-page applications.