Click here to Skip to main content
14,921,612 members
Articles / jQuery
Technical Blog
Posted 23 Oct 2012

Tagged as


6 bookmarked

Integrating Knockout and jQueryMobile

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
23 Oct 2012CPOL5 min read
Issues regarding integration of KnockoutJS and jQueryMobile, and a simple working example – a Twitter Search application – where the two technologies play nicely together!

This blog post looks at the issues regarding integration of KnockoutJS and jQueryMobile, and provides a simple working example – a Twitter Search application – where the two technologies play nicely together!

Image 1

The code for this blog post can be found on github. You can also try it out on your phone or browser.

Integration Woes!

Knockout is a great JavaScript framework for managing the various UI layers of your application, and I use it wherever possible. Recently, while I was working on an HTML5-based cross platform project Knockout was the obvious choice and for the Windows Phone version, it worked very well.

For the iOS version, I wanted to mimic the platform look and feel, which requires quite a lot of CSS, so rather than try to write this all myself, I opted for jQueryMobile (jQM) which is a well established framework for transforming HTML into iOS styled pages.

However, integrating Knockout and jQM poses something of a challenge. One of the biggest issues is that jQM is more than just a set of stylesheets; In order to support the iOS styling, it processes the DOM adding supporting structure. For example, a simple button is transformed from this:

<button type="submit" data-bind="enable: isSearchEnabled, click: executeSearch">Go</button>

to this:

<div class="ui-btn ui-btn-inline ui-btn-corner-all ui-shadow ui-btn-up-c">
  <span class="ui-btn-inner ui-btn-corner-all">
    <span class="ui-btn-text">Go</span>
  <input class="ui-btn-hidden" type="button" value="Go"
                  data-bind="enable: isSearchEnabled, 
                                    click: executeSearch"/>

This means that any changes to the DOM that occur as a result of changes to the underlying data (via the Knockout bindings) must then be further processed by jQM to add the structures that support the CSS.

My previous HTML5-based JavaScript applications have included a view model, the ApplicationViewModel, which exposes the top most view-model, which is rendered via a suitable template. This makes sense in that it reflects the way that native applications are written and navigated, making handling the Windows Phone back stack an easy task. Although this approach results in a lot of disruption to the DOM as pages are added / removes. Using this approach, I was unable to make jQM and Knockout play-nice and opted for simply copying the jQM stylesheets, which is far from ideal (you lose animations and end up with verbose HTML templates).

I decided it was time to re-visit this issue and see if I could come up with a better solution.

Integration -Take Two

The application I am going to present in this blog post is a simple Twitter Search application which I originally wrote for an MSDN Magazine article. It has three view models, each of which has a template which is rendered into the DOM when the user navigates from one page to the next.

I found anecdotal evidence on the web that it was not advisable to re-bind parts of the DOM using ko.applyBindings, this coupled with the fact that it is best to provide jQM with the entire application markup and allow it to do its ‘thing’ all in one go, lead me to try a different approach …

I removed all of the templates and placed them directly within the HTML document, using the standard jQM approach of adding an id for each page:

<!DOCTYPE html>
  <!-- ### A page that renders the TwitterSearchViewModel -->
  <div data-role="page" data-theme="b"
    <div data-role="header" data-theme="b">
      <h1>Twitter Search</h1>
    <div data-role="content" data-theme="c">
        <!-- search form -->
  <!-- ### A page that renders the SearchResultsViewModel -->
  <div data-role="page" data-theme="b" data-add-back-btn="true"
    <div data-role="header" data-theme="b">
    <div data-role="content" data-theme="c">
  <!-- ### A page that renders the TweetViewModel -->
  <div data-role="page" data-theme="b" data-add-back-btn="true"
    <div data-role="header" data-theme="b">
      <h1 data-bind="text: author">
    <div data-role="content" data-theme="c" class="tweet">
      <!-- a simple tweet view -->

Binding to this structure is simply a matter of creating view models that ‘back’ each jQM page and binding them via ko.applyBindings:

// create the various view models
var twitterSearchViewModel = new TwitterSearchViewModel(),
searchResultsViewModel = new SearchResultsViewModel(),
tweetViewModel = new TweetViewModel();
$(document).ready(function () {
  // bind each view model to a jQueryMobile page
  ko.applyBindings(twitterSearchViewModel, document.getElementById("twitterSearchView"));
  ko.applyBindings(searchResultsViewModel, document.getElementById("searchResultsView"));
  ko.applyBindings(tweetViewModel, document.getElementById("tweetView"));

Note, I could have created a single view model that exposes each of the three view models above and bound this at the body element level. But this would add very little value, it would not make communication between view models any easier.

Page Navigation

The next problem to tackle is page navigation. With the Twitter Search application, the HTML for the search form is as follows:

<!-- search form -->
  <input type="search" name="search"
          data-bind="value: searchTerm, valueUpdate: 'afterkeydown'" />
  <input type="button" value="Go"
          data-bind="click: search" />

The TwitterSearchViewModel which this part of the page is bound to exposes the search function which queries twitter and navigates to the results page:

JavaScript = function () {
  /// <summary>
  /// Searches twitter for the current search term.
  /// </summary>
  if ($.trim(this.searchTerm()) === "") {
  twitterSearchService.searchForKeyword(that.searchTerm(), 1, function (tweets) {
    if (tweets.length > 0) {
      // store this search
      // navigate to the results view model
      searchResultsViewModel.init(that.searchTerm(), tweets);
      $.mobile.changePage("#" + searchResultsViewModel.template);
    } else {
      that.userMessage("There were no matches for the given search term");

The interesting code in the above snippet is this part:

// navigate to the results view model
searchResultsViewModel.init(that.searchTerm(), tweets);
$.mobile.changePage("#" + searchResultsViewModel.template);

Here, we initialise the searchResultsViewModel which is global variable, providing it with the search result. The call to $.mobile.changePage causes jQM to ‘navigate’ to the next page via a fancy slide transition.

The SearchResultsViewModel takes the valus supplied by the init method and updates its bound observables:

function SearchResultsViewModel() {
  /// <summary>
  /// A view model that renders the results of a twitter search.
  /// </summary>
  var that = this,
      twitterSearchService = new TwitterSearchService();
  // --- properties
  this.template = "searchResultsView";
  this.tweets = ko.observableArray();
  this.pageNumber = ko.observable(1);
  this.searchString = "";
  // --- public functions
  this.init = function (searchText, tweetViewModels) {
    this.pageNumber = ko.observable(1);
    this.searchString = searchText;

Updating the state of the bound view model removes the need for re-binding. The same approach is used for navigating from the SearchResultsViewModel to the TweetViewModel, a single TweetViewModel instance is bound to the UI, with its state updated as required.

List Binding

The above code all works quite nicely apart from one snag – lists. A knockout foreach can result in new elements being added to the DOM, each of which have to be processed. Typically, a Knockout foreach would be used to populate a jQM listview, which performs all kinds of extra processing to ensure that each list item has the same height etc …

The approach I took is very similar to the one presented in this blog post, which adds a custom binding that ensures that the listview is made aware of new items being added. The one problem I found with the approach presented is that it worked for the initial population of the list, but subsequent updates did not update the custom binding. Combining this approach with a few tips I picked up from StackOverflow, I came up with this solution:

ko.virtualElements.allowedBindings.updateListviewOnChange = true;
ko.bindingHandlers.updateListviewOnChange = {
  update: function (element, valueAccessor) {
    ko.utils.unwrapObservable(valueAccessor());  //grab dependency
    // locate the listview
    var listview = $(element).parents()
    if (listview) {
      try {
      } catch (e) {
        // if the listview is not initialised, the above call with throw an exception
        // there doe snot appear to be any way to easily test for this state, so
        // we just swallow the exception here.

The above is a custom binding that peforms some special logic each time the binding source changes. It locates the jQM listview, which could be the element that the binding is defined upon, or some parent (via a pretty funky jQuery tree traversal ‘query’). When the listview is found, listview('refresh') is invoked, which causes it to re-process all the list items, adding the required jQM markup to any newly added elements.

The ko.virtualElements.allowedBindings line allows this approach to be used for containerless Knockout bindings.

You can see this approach used in practice on the front page of the application where it displays the recent search terms:

<ul data-role="listview"
    data-bind="foreach: recentSearches, updateTableEachTimeItChanges:recentSearches">
    <a data-bind="click: $parent.recentSearchClicked">
      <span data-bind="text: $data"></span>

And in the search results view where it is used in the containerless form:

<div data-role="content" data-theme="c">
  <!-- twitter search results -->
  <ul data-role="listview">
    <!-- ko foreach: tweets, updateListviewOnChange:tweets -->
      <a data-bind="click: $parent.tweetClicked">
        <div class="thumbnail-container">
          <img data-bind="attr: { src: thumbnail }" />
        <h3 class="author" data-bind="text: author"></h3>
        <p class="text" data-bind="text: text"></p>
      <!-- /ko -->
      <a data-bind="click: loadMore" href="#">
        <h3 data-bind="visible: !isSearching()">Load more ...</h3>
        <h3 data-bind="visible: isSearching()">Loading ...</h3>

It’s a pretty simple solution, but it took a lot of trial and error to reach this point!

Finally, the iScroll integration, which I previously attempted myself is now achieved via the jquery-mobile-iscrollview plugin, which works like a charm. Just add data-iscroll to any page content and it will scroll.

The code for this blog post can be found on github. You can also try it out on your phone or browser.

Colin E.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Colin Eberhardt
Architect Scott Logic
United Kingdom United Kingdom
I am CTO at ShinobiControls, a team of iOS developers who are carefully crafting iOS charts, grids and controls for making your applications awesome.

I am a Technical Architect for Visiblox which have developed the world's fastest WPF / Silverlight and WP7 charts.

I am also a Technical Evangelist at Scott Logic, a provider of bespoke financial software and consultancy for the retail and investment banking, stockbroking, asset management and hedge fund communities.

Visit my blog - Colin Eberhardt's Adventures in .NET.

Follow me on Twitter - @ColinEberhardt


Comments and Discussions

QuestionUpdate to the new twitter API? Pin
Member 1072227017-Apr-15 3:14
MemberMember 1072227017-Apr-15 3:14 
QuestionIs there an easy way to split the main html page? Pin
SE_GEEK8-Nov-12 4:52
MemberSE_GEEK8-Nov-12 4:52 
Hi Colin,
I appreciate your post I am trying to write a jQueryMobile app using knockout myself. I cringe at the thought of having all of the view (html) in just 1 file, have you found a way to split these up?
I have tried to get this to work, but unfortunately I can't get the ko.applyBindings to trigger when the new page loads. For example if I have index.html with a link to page2.html, inside of page2.html have a page div called 'page2', and I have some javascript that looks like this:

$('#page2').on('pagecreate', function(event){
  ko.applyBindings( page2viewmodel, $('#page2')[0]);

I have tried using using every page event I can think of, and it works fine if I load page2.html directly, but if I get there from index.html none of the events I register even fire. Am I missing something here? Or is this difficulty why everything I seem to find has people just throw all the html into a single page?
Truly wise men don't play leap frog with Unicorns.

AnswerRe: Is there an easy way to split the main html page? Pin
Member 100406999-May-13 8:59
MemberMember 100406999-May-13 8:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.