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 JAVASCRIPT}});});func(innerItem, outerItem);cheeseUtils.composeString = function(bindingConfig ) {var result = bindingConfig.value;if (bindingConfig.prefix) { result = bindingConfig.prefix + result; }if (bindingConfig.suffix) { result += bindingConfig.suffix;}return result;}To create the namespace effect, I create an object and then assign my functions and variables asproperties within it. This means that to access these functions elsewhere, I have to use the name of theobject as a prefix, like this:cheeseUtils.map<strong>Pro</strong>ducts(function(item) {if (item.id == id) { item.quantity(0); }}, cheeseModel.products, "items");To be clear, this isn’t a real namespace because <strong>JavaScript</strong> doesn’t support them; it just looks andacts a little bit like one. But it is enough to reduce pollution of the global namespace, in that I have takentwo functions out of the shared context and replaced them with a single object name, cheeseUtils.There is still a risk of name collision, so it is important to select a name <strong>for</strong> the object that is specificto your project or area of functionality. You can nest namespaces by nesting objects, creating a hierarchythat must be navigated in order to use your code. Listing 9-2 shows an example.• Tip To save space, I won’t list all of the functions that are in the utils.js file. I’ll just pick some representativesamples to demonstrate the different techniques.Listing 9-2. Creating Nested Namespacesif (!com) {var com = {};}com.cheeselux = {};com.cheeselux.utils = {};com.cheeselux.utils.map<strong>Pro</strong>ducts = function(func, data, indexer) {$.each(data, function(outerIndex, outerItem) {$.each(outerItem[indexer], function(itemIndex, innerItem) {func(innerItem, outerItem);});});}com.cheeselux.utils.composeString = function(bindingConfig ) {var result = bindingConfig.value;231www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!