Book Review: Instant Dependency Management with RequireJS How-to

Asynchronous Module Definition
Instant Dependency Management with RequireJS How-to
Instant Dependency Management with RequireJS How-to from Packt Publishing

Greg Franko’s book, Instant Dependency Management with RequireJS How-to, from Packt Publishing, strives to cut through the clutter and introduce you to AMD through Require.js

Asynchronous Module Definition is a term that can be intimidating. Even worse, it can potentially discourage JavaScript programmers from learning about and implementing the AMD API.  Fortunately, this book can be helpful.

The initial areas of discussion. are what you might expect: learning how to load Require.js both synchronously and asynchronously, as well as setting Require.js configuration values. But what becomes apparent is that implementing AMD patterns does not mean having to abandon the tools you use. Mr. Franko does a nice job of illustrating how jQuery can be exposed in your pages as an AMD module, as well as Jasmine unit tests and client-side JavaScript templating. All of this is accomplished by leveraging Require.js. A logical extension of this journey is a discussion of JavaScript libraries that do not expose themselves as AMD modules such as Backbone.js and jQueryUI Widget Factory. In these cases, a thorough explanation details how to work around this challenge, and keep tight control of your JavaScript resources. There is also helpful content here for mobile web developers.

Instant Dependency Management with RequireJS How-to may not be the definitive “go-to” resource for those who are completely new to the concept of AMD or Require.js. While key concepts are well served, this book’s strength is its ability to broaden one’s perspective with regards to what Require.js is capable of. By illustrating jQuery’s ability to be exposed as an AMD module, the power and flexibility of Require.js becomes increasingly apparent.

I would recommend this book for JavaScript developers who are already familiar with the concept of asynchronous module definition and understand in general how Require.js works. For this audience, Mr Franko’s direction will deliver a great deal of value with regards to the numerous architectural solutions that are detailed. In each case it is easy to see that Reqiure.js is more than simply a sophisticated script loader. This library exposes a number of properties and methods that help you to leverage AMD as broadly as possible, even when some of the libraries in use are not AMD compliant.

Instant Dependency Management with RequireJS How-to is available in paperback, or eBook format.

  • Author: Greg Franko
  • File Size: 100 KB
  • Print Length: 42 pages
  • Publisher: Packt Publishing
  • Publish Date: May 22, 2013
  • Language: English
  • ASIN: B00CXRTC1Q

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/

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