Book Review: Node for Front-End Developers, by Garann Means

Node.js

Node for Front-End Developers, by Garann Means - CoverIf you are just getting started with server-side JavaScript, “Node for Front-End Developers” offers a fast, high-quality introduction.

The ubiquity of front-end JavaScript is undeniable. Not only has the appetite for web-based content increased dramatically, but so has the appetite for sophisticated user interfaces. More and more, visitors expect web-based content to offer complex interaction and high-performance. The explosion of mobile device use has only exacerbated this dynamic. Ryan Dahl’s Node.js turned the whole concept of JavaScript on its head by providing an open-source tool that allows the language to be leveraged on the server-side, significantly expanding the potential of this language.

Node for Front-End Developers, by Garann Means is a fast introduction to this incredibly powerful technology. The concept of creating a web-server provides a door through which clear and concise explanations present the basic concepts of server-side JavaScript. I found it particularly helpful that for such a short book, topics such as the query string, post data, path data routing, asynchronous events, templating, databases and MVC are well handled.

The book’s length is deceptive; readers will find a wealth of useful information here. While each topic represents a thread that deserves further reading, anyone who is new to Node.js will find Ms. Means’ introduction helpful. Her writing style is both relaxed and professional. From using NPM to install modules, to real-time communication with WebSockets, Node for Front-End Developers offers a range that is just enough to excite the reader, yet never too much detail. Any of the examples can be typed into your favorite text editor and fired-up with minimal effort. This is critical when delving into a new topic, and makes your introduction to Node.js disarming and fun.

  • Title: Node for Front-End Developers
  • Author: Garann Means
  • Publisher: O’Reilly Media
  • Date Published: February 7, 2012
  • Language: English
  • ISBN-10: 1449318835
  • ISBN-13: 978-1449318833

Cross-Browser Asynchronous JavaScript Script Loading

Asynchronous

JavaScript LogoWhile it is perfectly normal to have one or more JavaScript tags in your markup as prerequisites to your code, there may be situations in which you want to avoid this

When I build a piece of functionality that is contained in one JavaScript file, I try to avoid asking the back-end developer to include additional scripts in the markup. So, my philosophy is: my script provides a certain “chunk” of functionality. Whatever external resources my script depends on are my script’s problem and will be handled accordingly. As often as possible, I’d like the consumer to simply choose to use or not use my script. This decision should involve simply adding or removing my script from the markup. The remaining abstraction is my responsibility.

This may seem a bit altruistic, but so far I’ve never had to lower my standards on the issue. The key to keeping this philosophy is, of course, the ability to reliably load other scripts asynchronously. I say “reliably” because it’s not enough to simply inject the script into the head of the document. You need to know when that script has successfully loaded before you take further actions that depend on the script.

The good news is: modern browsers provide the “onload” event, allowing you to set up your handler without too much effort. But the bad new is: Microsoft’s Internet Explorer 8 and below do not implement that event. So, there is some work to do. It’s not too bad; it just means we need to fork our code a bit.

Oh, and by the way; you might be wondering why I didn’t simply use the jQuery.getScript() method. jQuery is awesome and we all love it more than coconut ice cream. But I strongly believe that it’s important to know how to do these things with native JavaScript. One day a client will tell you that for whatever reason, you can’t use jQuery. When that day comes, you’ll be ready.

So let’s have at it!

Example # 1

Now here in Example # 1, we’ve created a function that takes a URL and a callback as arguments. The URL is required, the callback is optional. As you can see, this is pretty straightforward stuff:

  1. Create a script DOM element
  2. Assign an anonymous function to the “onload” event
  3. Set the script’s source
  4. Inject the script into the DOM

No worries.

Example # 2

In Example # 2 we have rolled up our pant legs and stepped into the cold wet mud that is Internet Explorer 8 (and below). So here we will need to assign that same anonymous function to the script element’s “onreadystatechange” property. And this property will change as the “ready state” of the script element updates. When that ready state is “loaded”, then we can be confident that the external script has successfully loaded and executed. It’s a bit more work, but then again, Internet Explorer wouldn’t be such a charming little browser if it adhered to the same kind of common-sense standards as every other modern browser on the planet… but I digress.

Example # 3

Well… Example # 3 certainly contains a bit more code, huh? In fairness, it’s heavily commented. But outside of that, what has happened is that as promised, we’ve forked the code so that we can support good ol’ IE, as well as all the other browsers that are made by sane people. I chose to check for the existence of document.attachEvent as a way of sniffing the browser. Some may disagree, but for me, it has always worked just fine.

If you follow the link to the full working example below, be sure to open your JavaScript console. When you do, you’ll see that the message from the actual external script always fires before the callback. Always. This is what we needed: the ability to load the script, and reliably know when it has loaded so that we can safely assume whatever resources it provides are available to us. So go ahead and try it in Internet Explorer 8 or Internet Explorer 7; it works just fine.

The full working example can be found here: http://examples.kevinchisholm.com/javascript/script-loading/

Summary

In this article, we learned how to implement a reliable solution for cross-browser asynchronous JavaScript loading. We discussed the need to fork our code in order to support Internet Explorer 8 (and below), and the “onreadystatechange” event that it implements.

Helpful Links for JavaScript loading

http://css-tricks.com/thinking-async/

http://friendlybit.com/js/lazy-loading-asyncronous-javascript/

Book Review: Async JavaScript, by Trevor Burnham

Asynchronous

Async JavaScript, by Trevor Burnham - CoverLearn to master the tricky nature of asynchronous JavaScript with “Async JavaScript – Recipes for Event-Driven Code“. This short yet thorough book explains many concepts which not only demystify the subject, but also arm you with tools to architect smarter solutions.

There are books that explain how JavaScript works, and then there are books that transform your perception of the language. Trevor Burnham’s “Async JavaScript” is the latter.

Maybe you had your first JavaScript “aha!” moment when you used the document.addEventListener() method to create your first click handler. Or maybe it was the wonderment of running some free-form code in the console and watching the web page change. Regardless of which context kicked-off your fascination with JavaScript, the intimate relationship between the DOM and this dynamic language is one of the things that make it so special. That “real time” aspect of JavaScript development is addictive.

But once you ascend to real-world problem solving, the asynchronous nature of JavaScript can be a buzzkill. The only way to slay this dragon and return to the zombie-like euphoria of JavaScript development is to dive into this topic, master it, and then gently place your sword back into its sheath.

It can be done.

Async JavaScript covers every angle and does it quite well. Starting with the JavaScript event model, it introduces you to the tricky nature of how the language handles events. Mr. Burnham then provides a surprisingly refreshing explanation on the setTimeout() and setInterval() methods, rescuing them from the “anti-pattern” monikers they have unfairly accumulated over time because of their improper use.

Before you can count to 100 milliseconds, you are whisked away, into a whirlwind of concepts that help to demystify JavaScript’s asynchronous nature. In a clear and concise manner, concepts such as the Pub/Sub model, custom events, Promises/Deferreds and Web Workers are detailed, as well as numerous libraries that help to implement these patterns.

I can’t recommend this book enough. As you start to write intermediate-level JavaScript, you find pebbles in your shoe. Quite often, these pebbles arise from tricky asynchronous JavaScript problems. Async JavaScript by Trevor Burnham is an invaluable resource. It not only explains how JavaScript processes events, but also provides numerous perspectives that help to understand and master its asynchronous nature.

Note: This book is no longer available in paperback, just the Kindle edition. It has been revised and updated, and is now a “PragProg” book.

  • Title: Async JavaScript
  • Author: Trevor Burnham
  • Publisher: Leanpub
  • Publication Date: March 20, 2012
  • Print Length: 88 pages
  • Language: English
  • ASIN: B007N81FE2
  • ISBN: 1475247362

Using jQuery Deferred to Manage Multiple AJAX calls

jQuery

jQuery LogoOnce you have become accustomed to making AJAX calls and consuming the contents of the data returned by the server, it is tempting to fall into a laid-back mind set: “hey, AJAX is AJAX right?… I mean… you open the request, you send the request, you wait for the server’s response, and then you do something with the response… no big deal, right?”

Well, yes, but… because of the asynchronous nature of an AJAX call, it does not take long for more complex scenarios to arise. What happens when you need to know about a group of AJAX calls? How can we treat a series of asynchronous events as a single value that we need to act upon once there is a collective “success” value?

Enter the jQuery.when() method. This handy dandy little tool allows you to treat multiple asynchronous events as a single value. The syntax is quite simple:

var B = $.get(serverPage.xyz); var C = $.get(serverPage.xyz); $.when(A,B,C).done(funtion(){ //act upon the collective success of A,B and C });

Some might find this a bit unusual. Normally, an AJAX call is something you simply “do,” not something you assign to a variable. jQuery allows us to treat an AJAX call as a value. This value translates to an object that has properties and methods. The $.when() method knows how to recognize and act upon these objects, so it presents a perfect way to handle multiple asynchronous events as a single value.

Example # 1

In Example # 1, we create the variable “aj1”, and set it to equal the result of an AJAX call. This variable becomes a jQuery “jqXHR” object. When we immediately inspect the object, we see that it has a number of methods. This is interesting, but not super interesting.

If you open your JavaScript console and then run this code, you will see the AJAX call in progress, and the contents of the jQuery “jqXHR” object. But if you wait a few seconds, and then after the AJAX call completes, you once again run the code: console.dir(aj1), you will see that this object has changed a bit. The “readyState” property is equal to 4, the “responseText” property contains some HTML from the server, the “status” property is equal to 200, and the statusText is: “OK”. Because the AJAX request has completed, this jqXHR object has properties that reflect this new state.

Example # 2

In Example # 2, we use the jQuery.when() method to act upon the completed state of the AJAX request. When using this syntax, the completed state of each request is a corresponding argument in the anonymous function that is passed to the .done() method. Now we have something interesting, because what we see is that each one of these success objects is an array. The first element is the response text of the request, the second element is the status of the request, and the third element is the original “jqXHR” object.

Example # 3

In Example # 3, we set up three AJAX calls. Normally, one might create a success handler for each AJAX call. In this case, we simply want to know when all three calls have completed successfully. We pass all three AJAX calls (i.e. the three variables that have been assigned the return value of each AJAX call), as arguments to the .when() method. Then we pass an anonymous function to the .done() method that is chained to the .when() method’s return value.

Just as with Example # 2, we take the success object for each call as the corresponding argument of the .done() method call. Inside of the .done() method’s callback, we take action; the contents of the $(‘#target’) element is removed, and we append the server response messages to that element.

Here is the full working example: http://examples.kevinchisholm.com/jquery/when/example-1/

Summary

If you have not had to wrestle with a scenario like this, you soon will. You’ll find that as web pages become more complex, AJAX is leveraged in more complex ways. When asynchronous activity is involved, any complexity is magnified. So, fortunately, the jQuery.when() method is an easy and effective way to handle multiple AJAX calls as one collective value.

Helpful Links for the jQuery.when() method

http://api.jquery.com/jQuery.when/

http://api.jquery.com/category/deferred-object/

http://stackoverflow.com/questions/5280699/jquery-when-understanding

 

Getting Started with Require.js – Part III

Asynchronous Module Definition

Require.js LogoLearn How to Build a Social Media Plugin, Using Require.js and the Asynchronous Module Definition (AMD) Pattern

In Getting Started with Require.js – Part II, we took a closer look at the way the Require.js JavaScript library works. We created modules that depended on other modules, and learned how the return value of a module can be used to expose functionality to the outside world.

In Part III of this series, we will use Require.JS to build a social media plugin. We’ll leverage the concepts and techniques used in Part II to create reusable front-end code that has real-world usefulness. You’ll be able to take the code from the completed working example, copy it, tweak it, and use it for your own web page.

Since we have discussed a great deal of Require.js implementation details, I’ll keep the discussion on a high level here. You can drill down into the code for a completed working example and review all of the nitty-gritty details if you like. The focus of this article is to provide an example that demonstrates how Require.js can be put to use in a real-world context.

Before we dive into the code, it might help to see the full working example for this article:

http://examples.kevinchisholm.com/javascript/requirejs/part-iii/

NOTE: For most of the examples, I will provide a link to the actual module file. I don’t think there is much point in repeating that same code here in the article. You can simply view it in your browser.

Example # 1

In Example # 1, we have the markup for our web page. You’ll notice that I have removed the CSS in the head and most of the content in the body. This is only to keep the code example short. Otherwise, it is identical to the working example.

In this example, after including require.js, we use the require() function. The first argument is social-menu.js. This is the only dependency for the JavaScript code in the page. In the anonymous function that is the second argument to the require() function, we reference social-menu.js as “menu”. We then call the init() method of the variable “menu”, which is an object. We know this because as we will see shortly, the return value of the module social-menu.js is an object with a method named init(). We pass an array to meunu.init(). This array contains strings that identify the social media icons we want to include in our plugin. Next, we will take a closer look at the module: social-menu.js.

social-menu.js

http://examples.kevinchisholm.com/javascript/requirejs/part-iii/social-menu.js

This module has one dependency: social-markup.js. Inside of our module, social-markup.js is referred to as “socialMarkup”. Inside of the init() method, we instantiate the socialMarkup() constructor. We then use the getLinks() method of the socialMarkup() object. When past the appropriate array, the getLinks() method will return a DOM object that only needs be appended to the DOM, which we do on the very next line.

The beauty of this Asynchronous Module Definition (AMD) pattern is that as we step through the code, the implementation details of each dependency is abstracted away by the module that we depend on. We simply “need” that module, Require.js loads it asynchronously for us, and then we use it. This makes it easier to follow and understand code that you did not write. As you follow the dependency chain, digging deeper into the code, you can see more implementation details (if you choose to do so).

social-markup.js

http://examples.kevinchisholm.com/javascript/requirejs/part-iii/social-markup.js

If you look towards the bottom of this module, you’ll see that it returns a function. That function is meant to be used as a constructor. The line “this.getLinks = function(arr){…” indicates that when instantiated, the resulting object will have a method named “getLinks()”. The private variables “makeAnchor”, “addTitle”, “addClickHandler” and “makeImage” are all helper functions that handle the implementation work needed to create the DOM object that this module returns. Lastly, notice that this module’s sole dependency is “social-icons.js”, which contains the data we need to construct the actual social media icons and event handlers.

social-icons.js

http://examples.kevinchisholm.com/javascript/requirejs/part-iii/social-icons.js

This module has no dependencies. It returns an object whose properties are all objects containing data for each social media type. Each of those individually named objects has the following properties:

  • Image: A data URI that provides an image, so that we don’t need to reference external resources.
  • Title: What users see when they hover over the icon.
  • Handler: A function that will be the click-event handler for that social media icon.

Now that we have taken a high-level view of the code, re-visit the full working example for this article:

http://examples.kevinchisholm.com/javascript/requirejs/part-iii/

In the full working example, you’ll notice that each social media icon allows you to share the page (e.g., “tweet” “pin”, “facebook post”, etc…). These actions are determined by the click event handler that we specified for each icon in the module: social-icons.js. The images for icons themselves are provided by the data URL for each social media type (once again in “social-icons.js”), as well as the title that you see when you hover the mouse over that icon.

Summary

In this article, we put to use, in a real-world context, the concepts and techniques that we learned in Part I and Part II. We created a social media plugin that actually works. I hope you have enjoyed this series. Require.js is a powerful and helpful JavaScript library that helps you to create loosely-coupled, modular, reusable code.

Helpful Links for Require.js and Asynchronous Module Definition (AMD)

Require.js

http://requirejs.org/

http://www.webdesignerdepot.com/2013/02/optimize-your-javascript-with-requirejs/

Asynchronous Module Definition (AMD)

http://stackoverflow.com/questions/12455537/asynchronous-module-definition-difference-between-beta-verb-and-requirebeta

http://www.sitepen.com/blog/2012/06/25/amd-the-definitive-source/

http://blog.davidpadbury.com/2011/08/21/javascript-modules/

Using the jQuery Promise Interface to Avoid the AJAX Pyramid of Doom

jQuery

jQuery LogoNested success callbacks are messy business. The jQuery Promise interface provides a simple and elegant solution.

So, you have to make an AJAX call, and then do something with the return data. No problem, right? Right. What if you have to make two AJAX calls, and then do something with the return data for each one? No problem, right? Right. What if the second AJAX call depends on the success of the first AJAX call?

“…um, well…. then, well… wait a minute… ok, I’ve got it:

I’ll make the first AJAX call…and then inside the success callback function, cache the data somewhere… um… in a global variable for now I guess… yeah, no one will notice. OK, and then inside of that success callback, we’ll nest another AJAX call, and then inside of the second AJAX calls’ success callback, we’ll get our first chunk of data from the global variable, and then, and then… um…and then…”

…yikes!

Obviously, the preceding diatribe was a little over the top, but c’mon…. haven’t you at least once stood at the edge of that cliff and looked over? Fortunately, jQuery features a way out of this mess that is safe, reliable and packed with vitamins.

The jqXHR object

Since version 1.5.1, jqXHR objects returned by $.ajax() implement a “Promise” interface. In short, this means that a number of methods that are exposed provide powerful abstraction for handling multiple asynchronous tasks.

I think it is important to note that the subject of the jQuery Deferred and Promise Objects is deep. It is not an easy topic to jump into and a detailed discussion of this is outside of the scope of this article. What I hope to accomplish here is to provide a simple and fast introduction to the topic, by using a real-world problem / solution.

There are certainly multiple scenarios in which the jQuery Deferred and Promise objects can be useful. I have chosen to use AJAX calls for this, since it is an example of asynchronous behavior that I think most folks can relate to. In order to dramatize the effect of an asynchronous AJAX call, I am using a PHP file that can return a delayed response. Here is the code for the server page:

OK, now some AJAX.

(Note: I highly recommend that you open up the “network”  panel in Firebug or WebKit developer tools so that you can see these AJAX calls in action when viewing the working examples… especially AJAX call # 1, which will take 5 seconds to complete)

Example # 1

In Example # 1 we have a fairly straightforward setup: Two buttons, each resulting in an AJAX call. Notice that the 1st AJAX call takes 5 seconds to complete. Instead of providing an inline anonymous function for the success callback of each AJAX call, we have a generic handler named “success”.

Here is a link to the working code for Example # 1: http://examples.kevinchisholm.com/jquery/promise/promise-and-ajax-beginner/example-1.html

But what if we want AJAX call # 2 to depend on AJAX call # 1? That is, we don’t want AJAX call # 2 to even be possible until AJAX call # 1 has completed successfully.

Example # 2

In Example # 2, we have a pattern that is known as the “Pyramid of Doom”. This might work for the short term, but it is impractical, not at all flexible, and just plain messy. What if there was a third button, and a fourth button… I think you see what I’m getting at here.

Example # 3

Ahhh… that’s much better!

In Example # 3, we have taken advantage of the Promise interface that is exposed as part of the jqXHR object. If you are wondering what the jqXHR object is, it is the return value of any $.ajax() call. So, while you can simply do this: $.ajax(URL,CALLBACK), the call itself returns a value. That return value is the jqXHR object, which is a superset of the XMLHTTPRequest object.

The return value of $.ajax() is the jqXHR object, which is a superset of the XMLHTTPRequest object, and packed with some powerful features.

We don’t have to dive too deeply into the good ol’ XMLHTTPRequest object (although it is important to know what it is and the critical role that it plays in AJAX). But the key point here is that the jqXHR object wraps the XMLHTTPRequest object, providing some useful features. One of those features is the “Promise” interface.

“….ok, ok Kevin, you’re givin’ me a migraine… where are you going with all this?”

Hang in there; we are at the 99 yard line here. What this all means is that instead of just making an AJAX call, you can assign that AJAX call to a variable. Since the $.ajax() method returns the jqXHR object, your variable is now a Swiss Army knife of AJAXian goodness. You can then implement methods of your object (i.e. your variable). Two of those methods are: .when() and .done();

So, in Example # 3, when we fired the first AJAX call, we assigned its return value to the variable “aj1”. Notice that we did NOT make a success handler call. We simply make the AJAX call, and that call’s return value is held by the variable “aj1”. Then when the user clicks the second button. we set the return value of the second AJAX call to the variable: “aj2”. Now we have two variables and each is a jqXHR object. These are powerful little objects!

The line where the fun really starts is: $.when(aj1,aj2).done()

Notice how the .done() function takes a callback. The callback is fired when the two arguments passed to the .when() method are resolved. And guess what those two arguments are… our two little jqXHR objects!

So, the .done() method knows how to get ahold of the data returned by each of those calls. Now we simply call our generic success handler, passing in the return data of each AJAX call (i.e. each jqXHR object). You may be wondering why I pass in the values “a[0]” and “b[0]”. This is because “a” and “b” are jqXHR objects. It just so happens that the first property of these objects (i.e. the property with the index of 0) happens to be the “responseText” property of that object (i.e. the text sent back from the server).

Phew!

I know that was a lot. But there is much to shout about when it comes to the jQuery Promise interface. As I mentioned, it is a big topic and not easily summarized. But my hope is that these examples will have put a little context around the subject, and will help you to dive in and get started.

Below is the source code for this article’s full working example:

Example # 4:

Here is a link to this article’s full working example: http://examples.kevinchisholm.com/jquery/promise/promise-and-ajax-beginner/example-2.html

Summary

In this article we learned about the jQuery Promise interface. We discovered that since version 1.5.1, calls to $.ajax() return a jqXHR object, which implements the Promise interface. We utilized the .when() and .done() methods of this interface to execute callback functions for two asynchronous tasks. This eliminates the need for nested success callback functions.

Helpful Links for the jQuery Deferred, jQuery Promise and jqXHR Objects

jQuery Deferred

http://api.jquery.com/category/deferred-object/

http://api.jquery.com/jQuery.Deferred/

jQuery Promise

http://api.jquery.com/promise/

http://api.jquery.com/deferred.promise/

http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/

jQuery jqXHR

http://api.jquery.com/Types/#jqXHR

http://api.jquery.com/jQuery.ajax/#jqXHR

Getting Started with Require.js – Part II

Asynchronous Module Definition

Require.js LogoStep beyond the basics, and learn how Require.js modules can return various kind of values, depend on other modules, and keep those dependencies transparent to the outside world

In Getting Started with Require.js Part I, we got to know the Require.js JavaScript library. We learned about the basics of the define() and require() methods, and how they load dependencies asynchronously and then provide access to the return value of each one.

In Part II of this series, we will use Require.JS to build a little application that displays the daily specials for a restaurant. It’s a silly little example, but perfect for taking our discussion of Require.js to the next step.

The focus of this article is to demonstrate how one module can depend on one or more modules, and each of them can have similar dependencies. The beauty of this approach is that when one module depends on another, it has no knowledge of, nor does it care about how many dependencies the module it needs may have. So for example:

index.html -> needs module-A
Module-A -> needs Module-B
Module-B -> needs Module-C and Module-D
Module-D – > needs Module-E

The beauty of this approach is that our web page index.html only cares about module-A. It has no idea that Module-A in turn needs Module-B. And so on. This approach encourages you to write code modules that are reusable, and less tightly coupled.

Before we dive into the code, it might help to see the full working example for this article:

http://examples.kevinchisholm.com/javascript/requirejs/part-ii/

NOTE: for most of the examples, I will provide a link to the actual module file. I don’t think there is much point in repeating that same code here in the article. You can simply view it in your browser.

Example # 1

menuData.js

http://examples.kevinchisholm.com/javascript/requirejs/part-ii/menuData.js

In Example # 1, we see the data that is used for this example. What is nice about the module pattern used here is that whenever this data needs to change, we only have to make that change in this one small file. The rest of the files that depend on this module have no knowledge of that, nor do they care. As long as the data is structured the way they expect, they don’t need to know about any changes to this module.

Example # 2

In Example # 2, we have the full source code for our web page. If you look at the require() statement, you’ll see that we have two modules as dependencies: css.js and menuMaker.js. Let’s follow the dependency tree, see what each module does, and then circle back to review the JavaScript in this page that responds to the button clicks. css.js http://examples.kevinchisholm.com/javascript/requirejs/part-ii/css.js This module simply injects a STYLE tag into the DOM. This is the CSS that makes the page look the way it does. Pretty simple stuff. menuMaker.js

http://examples.kevinchisholm.com/javascript/requirejs/part-ii/menuMaker.js

This module returns an object literal. That object has three properties. Each property is a DOM element: an unordered list (UL). None of these DOM elements exist in the page (yet) when they are returned, but they are valid unordered lists, waiting to be injected into the page. This module has two dependencies: weekParser.js and makeList.js. Inside of the anonymous function that wraps our module, they are referred to as: “weekTool” and “makeList.” We could have just as well called them “Sally” and “Sue”. It doesn’t matter. “weekTool” and “makeList.” are the variable names we chose. If you look at the object literal that is returned by menuMaker.js, you’ll see that we use “weekTool” and “makeList.” to create the object’s property values. weekParser.js

http://examples.kevinchisholm.com/javascript/requirejs/part-ii/weekParser.js

This module has the dependencies: ‘menuData’,’getDayType’. menuData is the array that contains our actual menu data. getDayType.js returns a sub-set of the ‘menuData’ array, depending on whether “weekday”, “weekend” is passed-in. getDayType.js

http://examples.kevinchisholm.com/javascript/requirejs/part-ii/getDayType.js

This module takes two arguments: the type of day (i.e. weekday or weekend), and the data array that contains the entire menu. Based on the type that was passed-in, it returns a sub-set of the array that contains only the days of type specified. makeList.js

http://examples.kevinchisholm.com/javascript/requirejs/part-ii/makeList.js

This module is unique amongst the modules we have reviewed so far in that it has no dependencies. It returns a function that takes one argument: an array. That array should contain the day objects that we want to turn into an unordered list. For each element in that array, it creates an LI element, puts the “Day” and “Menu” values into that LI, and then returns an unordered list (UL). Example # 3

In Example # 3, we circle back to our web page. This code does a quick check to make sure that the addEventListener() method is supported, and then gets to work setting up click event handlers for each of the three buttons at top.

Notice that in each case, menu.getFullWeek is the only reference to functionality provided by one of our modules. A simple call to a property of that module’s return value kicks off the dependency chain that we discussed above, but this web page neither knows nor cares about all that. It only knows that it required a file named “menuMaker.js”, it refers to its return value as “menu” and it wants the value of menu.getFullWeek (or menu.weekendMenu, etc…). The menuMaker.js module provides that functionality, and any other modules that it depends on in order to provide that functionality, are only of concern to menuMaker.js.

Summary

In this article, we created a web page that allows the user to view the weekday, weekend or full week specials for a restaurant. We demonstrated how modules can have dependencies on other modules, and that dependency chain can grow and become complex. The key takeaway here is that while this scenario may seem to be a one-way ticket to spaghetti code, it is quite the opposite; by following the Asynchronous Module Definition pattern, each one of our modules provides clear and distinct functionality. A module may depend on other modules, but it neither knows nor cares about the dependency chain that may exist with the modules that it depends on.

There is plenty more to discover with Require.js. But I hope this article has provided a helpful introduction to the library and the benefits of Asynchronous Module Definition patterns, beyond the basics.

Once again, here is the full working example for this article:

http://examples.kevinchisholm.com/javascript/requirejs/part-ii/

Helpful Links for Require.js and Asynchronous Module Definition

Require.js

http://requirejs.org/

http://www.adobe.com/devnet/html5/articles/javascript-architecture-requirejs-dependency-management.html

http://javascriptplayground.com/blog/2012/07/requirejs-amd-tutorial-introduction

Asynchronous Module Definition

http://requirejs.org/docs/whyamd.html

http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition

https://github.com/amdjs/amdjs-api/wiki/AMD

http://www.2ality.com/2011/10/amd.html

Getting Started with Require.js – Part I

Asynchronous Module Definition

Require.js LogoLearn how to decouple your code and organize it into reusable modules

Require.js is a JavaScript library that allows you to organize your code into separate modules. It follows the Asynchronous Module Definition API. Each module is an individual JavaScript file. You may, at first, bristle at this pattern because it forces you to rethink the way you organize your JavaScript. But while it may be a bit of an acquired taste, this approach encourages you to write code that is less coupled and easier to reuse.

The two methods that you will likely use the most are require() and define(). In both cases, you specify zero or more modules that your module “depends” on. When you do so, those modules will be loaded asynchronously. These dependencies are specified by a string which is a path to that JavaScript file. These strings must be in an array even if there is only one.

Following the array is an anonymous function. That function takes each dependency as an argument. What you do inside of that function is up to you. Just keep in mind that this function’s return value is what the outside world will “see” when they require your module.

Example # 1 A

Example # 1 B

Example # 1 A shows the code for our first module. It is a single JavaScript file named module-1.js. In that file, we execute the define() function. The define function takes a single argument, which is an anonymous function. In that function, we simply output some text to the console. Our module doesn’t do too much, but we’re keeping it simple for demonstration purposes.

In Example # 1B, we have the code for our web page. At the bottom of the page, we first pull in require.js. Then we execute the require() function. The first argument that it receives is an array. In this case, that array has only one element: “module-1”. That tells require: “hey, there is a file named ‘module-1.js’; load it asynchronously, and when that script has completed loading, run the following anonymous function.” In this example, the anonymous function has no code, so it does nothing.

Example # 2

In example # 2, we output some text to the console in the anonymous function. That console.log() call will only fire after module-1.js has loaded. This is where we start to see the brilliance of Require.js: you can have another module as a dependency, and your code will only execute once that dependency has loaded successfully.

Example # 3 A

Example # 3 B

In Examples # 3A and 3B, we see that we now have two modules. In each case, we output some text to the console, just to show that the module executes, and then each module returns a string.

Example # 3 C

In example # 3C, we pass an array with two elements as the first argument to the require() function: “module-1” and ,”module-2”. The anonymous function that is the second argument receives the return value of each member of that array. We can name these whatever we want. I used “mod1” and “mod2”, but I could just as well have named them “sally” and “sam”. It doesn’t matter; they are simply identifiers for the return value of each dependency. We demonstrate all of this by outputting the return value of each module to the console.

The working example for this article can be found here: http://examples.kevinchisholm.com/javascript/requirejs/part-i/

Summary

In this article, we were introduced to Require.js. We learned about how this JavaScript library allows you to organize your code into individual JavaScript files called “modules”. We learned about the define() and require() functions, their signatures, and how they are used in order to asynchronously load dependencies and create references to their return values.

Helpful Links for Require.js

http://requirejs.org/

http://blog.teamtreehouse.com/organize-your-code-with-requirejs

http://net.tutsplus.com/tag/requirejs/

http://requirejs.org/docs/whyamd.html

JavaScript Callback Functions – The Absolute Basics

Functions

JavaScript LogoCallbacks are a critical tool for properly handling asynchronous events in JavaScript.

Timing is one of the most difficult techniques to master in JavaScript. At first, many look to the setTimeout() method to address the asynchronous nature of JavaScript. But that is most often not the best approach. The concept of a callback function is one of the things that makes JavaScript such a special language.

In order to understand callbacks, it is important to be aware that functions are first class citizens in JavaScript. This means (among other things) that a function can be passed as a value to another function. The upside to this is the fact that if you call function A, and pass it function B as an argument, then inside of function A, you can execute function B. That’s really what it all boils down to: You call a function, and pass it another function. And inside of the first function, when an event that you need to complete has completed, you then “call back” to the function that was passed in.

While you can pass a named function as an argument, quite often you will see an anonymous function passed. Before we demonstrate a callback function, let’s demonstrate why they are so helpful in JavaScript.

Example # 1

PHP FIle:

Client-side JavaScript:

In Example # 1, we have two chunks of code: A server-side page that sleeps for three seconds, and then returns a JavaScript file. That JavaScript file simply outputs a message to the console.

When the script loads, it outputs a message to the console (message # 1). We want that message to be output before the 2nd message. The problem is that the script loading process is asynchronous; it could take 200ms, it could take five minutes. I’ve forced the PHP page that returns the JavaScript to “sleep” for three seconds, to exaggerate the effect. But the bottom line is: we don’t know how long that script loading process will take, which means that we have to find a way to execute message # 2 only after the script has finished loading.

Here is a JSFiddle link for Example # 1: http://jsfiddle.net/CZeLv/

Example # 2

In Example # 2, we pass an anonymous function to the getScript() method. Inside of getScript(), we take advantage of the fact that any dynamically loaded script element has an “onload” event. We assign that event to the callback that was passed-in. This means that when the script has successfully loaded, we execute the callback. As a result, we have complete control over the timing of events, even though the entire process is asynchronous. What happens is that message # 1 executes first, and then message # 2. This is what we want.

Here is a JSFiddle link for Example # 2: http://jsfiddle.net/dfCM2/

What if the script that we are loading has properties and methods that we need to act upon once the script is available? In Example # 3, we demonstrate how using a callback allows us to call a method that does not exist before the script is loaded, but we are able to control the timing of when it is called, so that it works every time.

Example # 3

PHP File:

Client-side JavaScript:

In Example # 3, after the PHP file “sleeps” for three seconds, it adds a new method to the window object. That method returns a secret word. We need access to that secret word in our page, but we need to make sure that we don’t try to call the method getSecretWord() until it is available. So by passing a callback to the getScript() function, we yield control to getScript() and basically ask it to fire our callback for us. Inside of getScript(), the script’s onload event is assigned to the callback, which means we only attempt to execute getSecretWord() once we know for sure that it exists (because the script’s onload event fired).

So the important thing to keep in mind here is that if the script we are loading takes five minutes to return, or never returns, it does not matter. Our callback will only fire when that script successfully loads. While it is loading, the user still has complete access to the browser. That is really important.

Here is a JSFiddle link for Example # 3: http://jsfiddle.net/fAn4g/

Summary

In this article, we covered the very basics of JavaScript callback functions. We learned that functions are first-class citizens in JavaScript, and can be passed to and from functions. We looked at an example of why callbacks are so critical to the JavaScript language and how they are an excellent tool for working around the asynchronous nature of the language,

Helpful Links for JavaScript Callback Functions

http://recurial.com/programming/understanding-callback-functions-in-javascript/

http://www.impressivewebs.com/callback-functions-javascript/

http://javascript.about.com/od/byexample/a/usingfunctions-callbackfunction-example.htm