12.07.2015 Views

Pro JavaScript for Web Apps pdf - EBook Free Download

Pro JavaScript for Web Apps pdf - EBook Free Download

Pro JavaScript for Web Apps pdf - EBook Free Download

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 8 CREATING MOBILE WEB APPSbe<strong>for</strong>e the view model is populated with the data bindings, which means that widgets are not createdproperly.This is the same problem I encountered previously with jQuery UI, but the issue is worse withjQuery Mobile because it assumes that it has sole control of elements in a page and makes it verydifficult to create bindings that can negotiate the extra elements that jQuery Mobile uses when it sets upa widget. (This is a problem I’ll return to <strong>for</strong> different reasons later in this chapter.)Disabling Automatic <strong>Pro</strong>cessingThe best approach is to prevent jQuery Mobile from automatically processing the document. To do this,I need to handle the mobileinit event, which is emitted by jQuery Mobile when the library is first loaded.I need to register my handler function be<strong>for</strong>e jQuery Mobile is loaded, which means I have to insert anew script element after the one that imports jQuery and be<strong>for</strong>e the one that imports jQuery Mobile,like this:...$(document).bind("mobileinit", function() {$.mobile.autoInitializePage = false;});...By setting the $.mobile.autoInitializePage property to false, I disable the jQuery Mobile featurethat processes the markup in the document automatically.• Tip To be fair, I need to insert my script element after jQuery only if I want to use the bind method, but Iprefer to do this rather than use the clunky DOM API <strong>for</strong> handling events.Disabling the automatic processing stops the race between the view model and jQuery Mobile andallows me to make my Ajax request, populate the view model, and do any other tasks I need withoutworrying about premature widget creation. When I am done setting up, I explicitly tell jQuery Mobilethat it should process the page, like this:$.getJSON("products.json", function(data) {cheeseModel.products = data;enhanceViewModel();$(document).ready(function() {ko.applyBindings(cheeseModel);$('button#left, button#right').live("click", function(e) {e.preventDefault();advanceCategory(e, e.target.id);})$.mobile.initializePage();212www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!