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!
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>
</span>
<input class="ui-btn-hidden" type="button" value="Go"
data-bind="enable: isSearchEnabled,
click: executeSearch"/>
</div>
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>
<html>
<head>
...
</head>
<body>
<!--
<div data-role="page" data-theme="b"
id="twitterSearchView">
<div data-role="header" data-theme="b">
<h1>Twitter Search</h1>
</div>
<div data-role="content" data-theme="c">
<div>
<!--
...
</div>
</div>
</div>
<!--
<div data-role="page" data-theme="b" data-add-back-btn="true"
id="searchResultsView">
<div data-role="header" data-theme="b">
<h1>Results</h1>
</div>
<div data-role="content" data-theme="c">
...
</div>
</div>
<!--
<div data-role="page" data-theme="b" data-add-back-btn="true"
id="tweetView">
<div data-role="header" data-theme="b">
<h1 data-bind="text: author">
</div>
<div data-role="content" data-theme="c" class="tweet">
<!--
...
</div>
</div>
</body>
</html>
Binding to this structure is simply a matter of creating view models that ‘back’ each jQM page and binding them via ko.applyBindings
:
var twitterSearchViewModel = new TwitterSearchViewModel(),
searchResultsViewModel = new SearchResultsViewModel(),
tweetViewModel = new TweetViewModel();
$(document).ready(function () {
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:
<!--
<form>
<input type="search" name="search"
data-bind="value: searchTerm, valueUpdate: 'afterkeydown'" />
<input type="button" value="Go"
data-bind="click: search" />
</form>
The TwitterSearchViewModel
which this part of the page is bound to exposes the search
function which queries twitter and navigates to the results page:
this.search = function () {
if ($.trim(this.searchTerm()) === "") {
return;
}
this.userMessage("");
this.isSearching(true);
twitterSearchService.searchForKeyword(that.searchTerm(), 1, function (tweets) {
if (tweets.length > 0) {
addSearchTermToRecentSearches();
searchResultsViewModel.init(that.searchTerm(), tweets);
$.mobile.changePage("#" + searchResultsViewModel.template);
} else {
that.userMessage("There were no matches for the given search term");
}
that.isSearching(false);
});
};
The interesting code in the above snippet is this part:
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() {
var that = this,
twitterSearchService = new TwitterSearchService();
this.template = "searchResultsView";
this.tweets = ko.observableArray();
this.pageNumber = ko.observable(1);
this.searchString = "";
this.init = function (searchText, tweetViewModels) {
this.tweets(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());
var listview = $(element).parents()
.andSelf()
.filter("[data-role='listview']");
if (listview) {
try {
$(listview).listview('refresh');
} catch (e) {
}
}
}
};
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">
<li>
<a data-bind="click: $parent.recentSearchClicked">
<span data-bind="text: $data"></span>
</a>
</li>
</ul>
And in the search results view where it is used in the containerless form:
<div data-role="content" data-theme="c">
<!--
<ul data-role="listview">
<!--
<li>
<a data-bind="click: $parent.tweetClicked">
<div class="thumbnail-container">
<img data-bind="attr: { src: thumbnail }" />
</div>
<h3 class="author" data-bind="text: author"></h3>
<p class="text" data-bind="text: text"></p>
</a>
</li>
<!--
<li>
<a data-bind="click: loadMore" href="#">
<h3 data-bind="visible: !isSearching()">Load more ...</h3>
<h3 data-bind="visible: isSearching()">Loading ...</h3>
</a>
</li>
</ul>
</div>
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.
Regards,
Colin E.