Recently I have been researching the use of PhoneGap for creating HTML5 Windows Phone 7 applications. I have written an introductory post on the subject and also managed to have a HTML5-based application accepted into the marketplace.

The Windows Phone 7 execution model has a few unique features (when compared to Android and iOS) that need to be considered when developing HTML5 applications. The first one, tombstoning, is something I dealt with in an earlier blogpost. In this post I want to look at how to handle the back-button and the application back-stack.

With Windows Phone 7, as the user navigates from one page to the next, the latest page is added to the top of a stack (the back-stack). The back-button is used to navigate back through the pages within your application by pulling them from the top of this stack. When the back stack holds a single page, i.e. the initial entry point into your application, pressing the back-button should exit the application.

So, how do you support this with a HTML5 / PhoneGap application? The PhoneGap APIs expose the back-button as a JavaScript event. If you subscribe to this event, your JavaScript code is notified each time the user hits the back button. Also, if the JavaScript event is subscribed to, the 'native' (C#) event is cancelled, which means application back-stack remains unchanged and your PhoneGap application does not exit.

In order to emulate the back-stack functionality in a PhoneGap application you need to subscribe to the PhoneGap backbutton when back-navigation is possible within your application, and unsubscribe when it is not. This means that when the user hits the back-button at the entry-point of your application, the application is terminated as expected.

A JavaScript Back-Stack

In order to handle the PhoenGap backbutton event, I felt the easiest approach would be to structure my JavaScript application so that it more closely resembles a Windows Phone 7 application. I have already discussed in my blog post on tombstoning how this task was made easier by using KnockoutJS to structure my code using the Model-View-ViewModel (MVVM) pattern.

In this blog I'll add further structure to the code, starting with an ApplicationViewModel. This view model contains a stack of view-models, with the one that is at the top of the stack, exposed via the currentViewModel observable property, being the one which is rendered on screen. The ApplicationViewModel also exposes functions for adding to and removing items from this stack:

function ApplicationViewModel() {

  var that = this;

  this.viewModelBackStack = ko.observableArray();

  this.backButtonRequired = ko.dependentObservable(function () {
    return this.viewModelBackStack().length > 1;
  }, this);

  this.currentViewModel = ko.dependentObservable(function () {
    return this.viewModelBackStack()[this.viewModelBackStack().length-1];
  }, this);

  this.navigateTo = function (viewModel) {
    this.viewModelBackStack.push(viewModel);
  }

  this.back = function () {
    this.viewModelBackStack.pop();
   }
}

The currentViewModel is implemented as a dependent-observable, a really neat KnockoutJS feature where you create a new observable property based on one or more observable properties of a view model. In this case, KnockoutJS does some magic behind the scenes to deduce that currentViewModel depends upon the viewModelBackStack observable array. Each time the array is modified, bindings that depend on currentViewModel are also updated. That's pretty neat!

The UI code needs to be modified so that the view relating to the currentViewModel is rendered and bound to its respective view model. This is simply a matter of subscribing to changes in this observable property in our code:

// create the view model
application = new ApplicationViewModel();

application.currentViewModel.subscribe(function (viewModel) {
  if (viewModel !== undefined) {
    $("#app").empty();
    $("#" + viewModel.template).tmpl("").appendTo("#app");
    ko.applyBindings(viewModel);
  }
});

application.navigateTo(new TwitterSearchViewModel());

For the above code to work, each view model must expose a template property which identified the HTML template which is their corresponding view. The above code creates a view instance and appends it to the #app element.

The templates for the two view-models within this application are shown below:

<script type=text/x-jquery-tmpl" charset="utf-8" id="twitterSearchView">
  <div>
    <form data-bind="submit: search">
        <input data-bind="value: searchTerm, valueUpdate: 'afterkeydown'" />
        <button type="submit" data-bind="enable: searchTerm().length > 0 && isSearching() == false">Go</button>
    </form>
    <ul data-bind="template: {name: 'tweetView', foreach: tweets}"> </ul>
  </div>
</script>

<script type="text/x-jquery-tmpl" charset="utf-8" id="tweetView">
  <li class="tweet"
    data-bind="click: select">
    <div class="thumbnailColumn">
      <img data-bind="attr: { src: thumbnail }" class="thumbnail"/>
    </div>
    <div class="detailsColumn">
      <div class="author" data-bind="text: author"/>
      <div class="text" data-bind="text: text"/>
      <div class="time" data-bind="text: time"/>
    </div>
  </li>
</script>

<script type="text/x-jquery-tmpl" charset="utf-8" id="tweetDetailView">
  <div class="tweet">
    <div class="thumbnailColumn">
      <img data-bind="attr: { src: thumbnail }" class="thumbnail"/>
    </div>
    <div class="detailsColumn">
      <div class="author" data-bind="text: author"/>
      <div class="text" data-bind="text: text"/>
      <div class="time" data-bind="text: time"/>
    </div>
  </div>
</script>

<h1 id="welcomeMsg">Twitter Search</h1>
<div id="app" />

When a tweet is clicked on, the select function is invoked via the Knockout binding. This simply pushes a TweetViewModel instance onto the application stack:

this.select = function () {
  application.navigateTo(this);
};

Handling the Back-Button

The above code navigates to the given view model, this will cause the currentViewModel dependent observable to notify that a change has occurred and the view that relates to this view model will be rendered. The next step is to wire up the back-button.

The ApplicationViewModel has a boolean backButtonRequired dependent observable that indicates whether the JavaScript code needs to handle the back-button. This is true whenever there is more than one item in the back-stack:

this.backButtonRequired = ko.dependentObservable(function () {
  return this.viewModelBackStack().length > 1;
}, this);

When the application is initially created, we handle changes to the observable as follows:

application.backButtonRequired.subscribe(function (backButtonRequired) {
  if (backButtonRequired) {
    document.addEventListener("backbutton", onBackButton, false);
  } else {
    document.removeEventListener("backbutton", onBackButton, false);
  }
});

function onBackButton() {
  application.back();
}

And that's it! When the JavaScript back-stack has more than one item, the PhoneGap backbutton event is handled and the back function invoked on our application, popping the top item from the stack, with the view updating accordingly. When our JavaScript back-stack has a single item, we no longer handle the PhoneGap backbutton event, this results in the Silverlight container handling the back-button. The Silverlight application back-stack always has a single page, so our application will exit.

This technique for handling the back-stack is simple and elegant, this example has just two simple pages, however this same pattern should scale well for more complex HTML5 applications.

You can download the full sourcecode here: PhoneGapBackStack.zip

Regards, Colin E.