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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 9 WRITING BETTER JAVASCRIPTfunctions to the namespace. If I need to change the name of the namespace, then I have to do it only inthe call to the createNamespace method (and, of course, in any code that relies on my functions). In thisexample, I have shortened my namespace by dropping the com prefix. The odds of there being a conflictare still pretty slim, but if it does arise, it is a simple enough matter to adapt.Using Self-executing FunctionsOne drawback of the previous technique is that I end up creating another global variable, utilsNS. Thisis still a better approach than defining all of my variables globally, but it is somewhat self-defeating.I can address this by using a self-executing function. This technique relies on the fact that a<strong>JavaScript</strong> variable defined within a function exists only within the scope of that function. The selfexecutingaspect means that the function runs without being explicitly invoked from another part of thecode. The trick is to define a function and have it execute immediately. It is easier to see the structure ofa self-executing function when there isn’t any other code:(function() {...statements go here...})();To make a function self-execute, you wrap it in parentheses and then apply another pair ofparentheses at the end. This defines and calls the function in a single step. Any variables defined withinthe function are tidied up after the function has finished executing and don’t end up in the globalnamespace. Listing 9-5 shows how I can apply this to my utility functions.Listing 9-5. Using a Self-executing Function to Define Namespaces(function() {function createNamespace(namespace) {var names = namespace.split('.');var obj = window;<strong>for</strong> (var i = 0; i < names.length; i++) {if (!obj[names[i]]) {obj = obj[names[i]] = {};} else {obj = obj[names[i]];}}return obj;};var utilsNS = createNamespace("cheeselux.utils");utilsNS.map<strong>Pro</strong>ducts = function(func, data, indexer) {$.each(data, function(outerIndex, outerItem) {$.each(outerItem[indexer], function(itemIndex, innerItem) {func(innerItem, outerItem);});});}utilsNS.composeString = function(bindingConfig) {var result = bindingConfig.value;234www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!