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 7 CREATING RESPONSIVE WEB APPS});});});});newCat : cheeseModel.products[0].category);I assign the object that the detectDeviceFeatures function passes to the callback to the deviceproperty in the view model. By using an observable data item, I disseminate changes into the applicationfrom the view model when the media query changes.The last step is to take advantage of the enhancements to the view model in the web app markup.Listing 7-6 shows how I can control the visibility of the CheeseLux logo through a data binding.Listing 7-6. Controlling Element Visibility Based on Screen Capability Expressed Through the View Model...Gourmet European Cheese...The result is to re-create the effect of using the CSS media query in <strong>JavaScript</strong>. The CheeseLux logois visible only on large screens. You might be wondering why I have gone to all the ef<strong>for</strong>t of re-creating asimple and elegant CSS technique in <strong>JavaScript</strong>. The reason is simple: pushing in<strong>for</strong>mation about thecapabilities of the device through my web app view model gives me a foundation <strong>for</strong> creating responsiveweb apps that are far more capable and flexible than would be possible with CSS alone. The followingsection gives an example.Deferring Image LoadingThe problem with simply hiding an img element is that the browser still loads it; it just never shows it tothe user. This is a ridiculous situation because it is costing me and the user bandwidth to download aresource that won’t ever be shown on a device with a small screen. To fix this, I have defined a new databinding called ifAttr in the utils.js file, as shown in Listing 7-7. This binding adds and removes anattribute based on evaluating a condition.Listing 7-7. A Data Binding <strong>for</strong> Conditionally Setting an element Attributeko.bindingHandlers.ifAttr = {update: function(element, accessor) {if (accessor().test) {$(element).attr(accessor().attr, accessor().value);} else {$(element).removeAttr(accessor().attr);}}}This binding expects a data object that contains three properties: the attr property specifies whichattribute I want to apply, the test property determines whether the attribute is added to the element,178www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!