This blog post looks at the issues regarding integration of KnockoutJS and jQueryMobile, and provides a simple worked 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:
To this:
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:
Binding to this structure is simply a matter of creating view models that 'back' each jQM page and binding them via ko.applyBindings
:
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 vie 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:
The TwitterSearchViewModel
which this part of the page is bound to exposes the search
function which queries twitter and navigates to the results page:
The interesting code in the above snippet is this part:
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:
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 adds a custom binding that ensures that the listview is made aware of new items being added. The one problem I found with this approach 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:
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:
And in the search results view where it is used in the containerless form:
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.