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 9 WRITING BETTER JAVASCRIPTUsing an AMD ModuleAMD solves the dependency issues by having a single resource loader take responsibility <strong>for</strong> loadinglibraries. This loader is responsible <strong>for</strong> executing a module’s factory function and ensuring that thelibraries it relies on are loaded and ready be<strong>for</strong>e this happens. The main means of communicationbetween a module and the loader is through the define function, which the loader is responsible <strong>for</strong>implementing.By standardizing the loading process, the decision about which loader to use is left to the consumerof AMD modules, rather than the author. So, I don’t have to worry about resolving dependencies when Iwrite an AMD module, and I don’t even have to worry about how they will be dealt with.Although the AMD <strong>for</strong>mat is gaining popularity, not all resource loaders support AMD. This includesModernizr.load, which I have been using to load libraries so far in this book (and to demonstrate whythis is a bad idea in this chapter). My favorite AMD-aware loader is requireJS, which you can downloadfrom http://requirejs.org. You can see how I have applied requireJS to my tiny web app in Listing 9-12.Listing 9-12. Using requireJS to Load AMD ModulesCheeseLuxvar libs = ['utils-amd','device-amd','custombindings-amd','jquery-1.7.1.js','knockout-2.0.0.js','modernizr-2.0.6.js'];require(libs, function(utils, device) {var cheeseModel = {selectedCount: ko.observable(0)};$(document).bind("mobileinit", function() {$.mobile.autoInitializePage = false;});$.getJSON("products.json", function(data) {cheeseModel.products = data;device.detectDeviceFeatures(function(deviceConfig) {cheeseModel.device = deviceConfig;$(document).ready(function() {ko.applyBindings(cheeseModel);246www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!