Using Backbone.js with jQuery Mobile
Backbone.js is an architectural framework that helps you write well-structured Web applications. It is not, however, a user interface framework and it therefore doesn’t help you with the way your application looks.
Backbone’s confined scope is a good thing: it’s lightweight, non-intrusive, not coupled to things you don’t need, and it lets you use the UI toolkit of your choice or simply roll your own styles and widgets. In my previous post, I demonstrated how to use Twitter Bootstrap on top of Backbone.
Quest for a Mobile UI Toolkit
After that post, I wanted to create a mobile version of the same application; a version that I could package with PhoneGap and that would look and behave like a native app. Twitter Bootstrap can probably be tweaked for that purpose as well, but I was looking for a UI toolkit dedicated to providing native looking controls and behaviors on mobile devices.
Another Way to Use jQuery Mobile
jQuery Mobile (jQM) is one option that I’ve explored before (here and here), but it fits more in the category of full-stack frameworks that tie together architectural structure and UI controls and behaviors. John Bender, my colleague at Adobe and member of the jQuery Mobile team, recently pointed out to me that you can disable the routing and navigation capabilities of jQM, and essentially use it as a pure UI framework on top of other architectural frameworks like Backbone.js.
Sample Application
I ended up spending a decent amount of time trying different things to get the two frameworks to play well together without stepping on each other. To save you some headaches if you are trying to do the same, I put together a simple application with the basic setup to combine Backbone (for the application structure and “routing”) and jQuery Mobile (for its styles and widgets).
NOTE: Another approach would be to use jQM’s “routing” instead of Backbone’s. Ben Nolan has an example of this approach here. I prefer to use Backbone’s routing because I find it more flexible and less “page-centric”.
Here is the app:
Click here to run the application in a separate window. The source code is available in this GitHub repository.
How it works
The key to this approach is to disable jQuery Mobile’s “routing”: In other words, you need to tell jQuery Mobile not to handle links, hash tag changes, and so on. I isolated that code in jqm-config.js:
$(document).bind("mobileinit", function () { $.mobile.ajaxEnabled = false; $.mobile.linkBindingEnabled = false; $.mobile.hashListeningEnabled = false; $.mobile.pushStateEnabled = false; });
If jQuery Mobile is not in charge of page navigation, you also have to manually remove the pages from the DOM when they are not used anymore. Here is one way to do it:
$('div[data-role="page"]').live('pagehide', function (event, ui) { $(event.currentTarget).remove(); });
With this configuration in place, you use Backbone’s routing as usual:
var AppRouter = Backbone.Router.extend({ routes:{ "":"home", "page1":"page1", "page2":"page2" }, home:function () { this.changePage(new HomeView()); }, page1:function () { this.changePage(new Page1View()); }, page2:function () { this.changePage(new Page2View()); }, changePage:function (page) { $(page.el).attr('data-role', 'page'); page.render(); $('body').append($(page.el)); $.mobile.changePage($(page.el), {changeHash:false}); } });
Is this the right stack?
I like the idea of a lightweight architectural framework combined with a UI toolkit. Backbone + Twitter Bootstrap felt right because the two frameworks have different areas of concern and complement each other very well. I was happy to see you could decouple jQM from its navigation infrastructure. However, that’s probably not the main “design center” at this point. I think it would be interesting for jQM to focus on that utilization scenario as well. At the end of the day, frameworks are often a matter of personal preferences, and not all applications are equal. So try it, see if it works for you, and share your experience. What UI toolkit are you using?
Source Code
The source code is available in this repository on GitHub.
A More Real-Life Application
In my next post, I’ll share a Backbone.js + jQuery Mobile version of the Employee Directory application first explored with Backbone.js + Twitter Bootstrap.
Follow Me
56 Responses to Using Backbone.js with jQuery Mobile
Trackbacks/Pingbacks
- March 8, 2012
[...] described in my previous post, jQuery Mobile was (at least initially) intended as a full-stack framework as opposed to a pure UI [...]
- - March 8, 2012
[...] described in my previous post, jQuery Mobile was (at least initially) intended as a full-stack framework as opposed to a pure UI [...]
- - March 8, 2012
[...] Using Backbone.js with jQuery Mobile Quest for a Mobile UI Toolkit After that post, I wanted to create a mobile version of the same application; a version that I could package with PhoneGap and that would look and behave like a native app. Twitter Bootstrap can probably be tweaked for that purpose as well, but I was looking for a UI toolkit dedicated to providing native looking controls and behaviors on mobile devices. Backbone’s confined scope is a good thing: it’s lightweight, non-intrusive, not coupled to things you don’t need, and it lets you use the UI toolkit of your choice or simply roll your own styles and widgets. In my previous post , I demonstrated how to use Twitter Bootstrap on top of Backbone. [...]
- - March 29, 2012 -
I’m working with other members of the jQuery Mobile community on the jQuery Mobile Cookbook (to be released by O’Reilly). There’s going to be an entire chapter on utilizing jQM for large scale applications. Connecting with Backbone and Knockout will be two the recipes.
Andy~
Has this book been published… I have been working on a jquery mobile project trying to plug it into mvc… but am having problems,
Would just like to point out that this posting has been immensely helpful in starting my project a couple of days ago. I had little experience in backbone and none in jQuery Mobile so knowing that the routing systems clashed was awesome.
I initially did things your way, but I’d like to share my method. I couldn’t get configuration on “mobileinit” to work consistently for some reason, so I listened to the “pagebeforechange” event.
// Prevent jqm from handling routes
$(document).on(‘pagebeforechange’, function(e, data){
// Only on url updates, non-jquery elements
if (typeof data.toPage === “string”) {
e.preventDefault();
var url = $(‘‘).attr(‘href’,data.toPage)[0].pathname; // Get our path
app.router.navigate(url, {trigger: true});
}
})
In my Route:
var page = new app.Views.TestPage();
page.render();
$.mobile.changePage($(page.el), {changeHash: false});
In addition, I put the jquery page enhancement stuff inside the views render method:
render: function(){
$(this.el).html(app.templates.test());
$(‘body’).append($(this.el));
$(this.el).page();
return this;
}
The main thing that bugged me about your solution is the use of the deprecated ‘live’ function. Why not just use ‘on’? Furthermore, we can put that event directly on the view:
views.TestPage = Backbone.View.extend({
events: {
‘pagehide’: ‘onPageHide’
},
…
onPageHide: function(){ $(this.el).remove(); }
});
Either way, thanks a lot!
Yeah, that’s all sorts of horrid formatting. Should be:
var url = $(‘<a />‘).attr(‘href’,data.toPage)[0].pathname; // Get our path
Hi John Fawcett,
thanks for your enhancement.
Do you have an full example somewhere public?
Thanks, dropping the jqm-config.js in my project fixed the navigation for me.
I feel your pain about the mobile UI toolkit. I have been on the quest to find the “right” mobile framework for some time now. My biggest issue is that I have a large web app who’s features keep growing, but to have this codebase also work for mobile has been a huge headache.
I started with Titanium, then moved to Sencha touch, which is where my mobile app resides. The problem is that the code is completely separate from my app so nothing is shared. I want to move to a Backbone.js powered UI that I could then “share” with my mobile apps. This solution comes close so I’m happy to see you struggling with the same issues. What I’d really love is to use Sencha Touch’s animations and UI components with Backbone but so far haven’t had any luck.
Do you do any freelancing work, I’d love to chat with you more about these experiences as I think we’re on the same page in terms of the mobile UI framework struggle.
Anyways awesome posts, I am going to read through the others and appreciate you taking the time to pave the path.
Thanks a lot for you ideas, I got my own backbonejs jquery mobile sample working :) if you want to you can check it out at https://github.com/ronaldpatino/backbone-namespace/tree/jqm. I think I can move to the next step now.
Thank you for the article, you saved the day. I have experimented a lot with this and also the other alternative (not using the backbone.js routing) and I like your approach.
I just want to add you don’t have to remove the pages from the DOM. They can still be there after you have changed the page. You will need to remove them only if you are afraid that the DOM will get too big, otherwise, you don’t need to. Correct me if I’m wrong.
One more thing, do you know a convenient way of how to set the transition, I mean every change page needs to have its own transition and the only way I figured how to do this is to pass the transition it in the url (which is ungly) or use global variable (which is still not very beautiful approach).
Thank you again!
Just to follow up above, to prevent the DOM from removing the elements, remove or comment this line from jqm-config.js
// $(‘div[data-role="page"]‘).live(‘pagehide’, function (event, ui) {
// $(event.currentTarget).remove();
// });
In this case, you will have to rearrange the router works so that views aren’t instantiated every time you switch pages, instead just load them up all at once. If they’re dependent on a model then trigger the model to re-render on change or reset.
you can use this.$el instead of $(this.el). fuckyeah backbone <3
This post helped me to solve a blocker in my project. But, my doubt now is, can we have the mobile gestures like, swipe, tap, swipe left etc as events in the view?
For example
Events:{
“tap #btnSignIn”:”doSignIn”
}
Does backbone support these mobile gestures?
Thank you for your post, it helped me alot to get started! :)
Thanks for the providing this.
I’m trying to figure out how to include a fixed footer navbar within this framework that navigates between the pages without reproducing it within each of the pages. Any hints as to how this would be done?
This is not working anymore with jquery.mobile-1.1.0.min.js
For me, it is working with 1.1.0 -
This was very helpful, thanks! Just curious if anyone else is having trouble with routes containing slashes when using this method. In my routes table I have an entry like “:page/:query” and it’s only getting hit after a second click. The first click seems to change the page’s url. Btw, it works if I change the slashes to some other character.
Thank you for your post, it was very helpful in getting backbone and jquery mobile working together.
Has anybody experienced problems with certain jquery mobile form controls such as the collapsible lists? In my case, when I let the router (with the changes you suggested) change me to a page that contains theses types of controls they don’t come out right. When I reload the page manually the page is rendered correctly. Any clues as to what might be causing this? (Other controls don’t have these problems)
Thanks for the tutorial. There is problem with footers/navbars though, it doesn’t show the active item in the bar unless you click 2 times in a row on the item, I think it’s because the way the changePage method in the router creates a new page and removes the old one… Don’t know yet how to fix that and some help would be appreciated! Thanks.
I appreciate this post. Earlier this year I built http://icon.spigit.com/. I used knockout.js with jQuery mobile and a CSS framework for responsive apps. I am pretty happy with this stack — it was very quick to get a clean integration going and my team was able to deliver the first release in a little over 3 months. For the first iteration I went with a stock implementation of jQM using the built-in link binding and hashchange mgmt. I was surprised with how far it got me. I added some state keeping params in the URL with BBQ also. Eventually, I want to clean up the URL window with more of a hash bang format and I am looking at pathjs for that. Thanks for this post — it is a great starting point for me to add in the new router.
FYI, the Backbone book, http://addyosmani.github.com/backbone-fundamentals/, talks about how to get Backbone and JQM to cooperate, by disabling JQM’s router. Search for “Backbone & jQuery Mobile”.
Actually the approach suggested in the Backbone book is not working. The minimun configuration I found working is: $.mobile.linkBindingEnabled = false; $.mobile.hashListeningEnabled = false;
Just discovered that the ‘pagehide’ event monitor needs to watch for dialogs as well:
$(‘div[data-role="page"],div[data-role="dialog"]‘).live(‘pagehide’, function (event, ui) {
$(event.currentTarget).remove();
});
gist here: https://gist.github.com/3369688
Thanks for the post! It is truly useful. Any news regarding the second part?
Use this routing method, it is difficult to show popup in new jquery mobile 1.2. Anyone can help?
How would you apply this technique on a website built on php?
Thanks
There’s a problem with jqm-config.js + with many options.
JQM renders in different ways depending on their sizes [see http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.js line 8553] . If the widget is too big JQM creates a new page and changes to it. When the execution gets line 3928 JQM tries to call active.url.indexOf( dialogHashKey ) , but active.url is undefined. Does anybody know how to solve this problem?
Using jQM with Knockout and Sammy, and using all the usual jQM config settings to allow Sammy to control routing (including $.mobile.linkBindingEnabled=false), but now older Android, particularly, has issues with link event handling. Not only are jQM link event styles unhooked (buttons and listview items don’t change color on touch), but the entire event goes unhandled. Touch events work reasonably well in most other phones. Anyone else experienced this and have a workaround they’ve used to fix the issue? I wish there were a config to just get jQM to handle touch abstraction and event UI, but leave routing to another framework.
Leandro,
Getting the same issue. Were you able to come up with a resolution?
https://github.com/jquery/jquery-mobile/issues/4202#issuecomment-8196553
Hi there.. love this but is can you suggest why this doesnt work on a windows phone 7? and what the possible solution may be? (apart from to get a better phone..)
Hi
I wanted to append the html in a div instead of body. But i am getting error.
I want to create 3 regions header, content and footer and only want to change the content area.
Thanks,
Sunny
Hey, this code saved me from a lot of headaches.
Thanks a lot!
If you are interested i’ve ported the javascript version of the code to coffeescript in https://gist.github.com/luiscronicl/4953670
two hours pulling my hair to trigger jqmobile restyle my page.
that’s the cure!
$.mobile.changePage($(page.el), {changeHash:false});
When pages scroll back, the direction is wrong!
Besides, I can still get the scent from fabric softener and dryer sheets.Tagged with cleaning productsI use Tide Simple Pleasures for all of my laundry. Simple fake louis vuitton coin pouch http://fakelouisvuittonspeedy.blogspot.com/
Hi, thanks for this post. It helped me a lot! Anyway if we are navigating from 1 page to another, do we still need to unbind the events attached to the previous page to avoid ghost views? Since I can see you only remove the page when rendering a new page like this:
// Remove page from DOM when it’s being replaced
$(‘div[data-role="page"]‘).live(‘pagehide’, function (event, ui) {
$(event.currentTarget).remove();
});
Should we do something like:
// Remove page from DOM when it’s being replaced
$(‘div[data-role="page"]‘).live(‘pagehide’, function (event, ui) {
$(event.currentTarget).remove();
$(event.currentTarget).close();
});
You’re a saint. Worked for me with jQM & angular.
Hi Mike,
Can you send sample of code on how you have done jQM with Angular please.
Thanks.
Thanks for any other informative site. The place else
may I get that kind of info written in such an ideal manner?
I have a venture that I’m just now running on, and I’ve been on the look
out for such information.
I was really searching for such a nice post…Thanks for sharing such a nice information, its beneficial for me…Keep sharing more.
Mobile Apps Development USA
Hey Christopher,
thanks for this nice article. Although it’s from 2012, this topic is still up-to-date. I’m using DurandalJs (http://durandaljs.com/), another cool modularization framework, to organize my webapps. I also want to combining it with jQuery Mobile and your configuration points me to the right direction :-)
Go on with this sort of articles.
Best regards,
Andi
Hi guys,
have you try to run this app in android emulator or maybe in IBBDemo2 – iPhone and iPad simulator, because this don’t work in them. I tried to run on android 2.3 device and it worked.
So I am confused a bit , does this combination of backbone + jqm work well on most platforms or this is just bug in simulators.
Do you have similar experience ??
Regards,
tommy
Hello,
thank you for this realy helpful information. We also develope Mobile Apps, and Backbone.js is also an option for us. But it sounds very interesting….
Nice post Christophe, I am using Kendo UI for current projects which is working well – great widgets and nice ‘native’ feel. Thanks again for the post.