Getting started with the filepath Node.js module

Node.js

Node.js LogoWhen you need to reference and work with the local file system in your Node.js program, the filepath module is quite a handy tool.

Even if your Node.js program is a web-server of some sort, working with the local file system is somewhat inevitable. While Node.js does provide low-level file system access (see the Node.js fs module), abstraction is always helpful, particularly when dealing with absolute paths.

The filepath Node.js module is a very helpful utility for simple access to file paths. You’ll need only a package.json file with this module as a dependency, an “npm install” command, and then you are up and running. This article provides a quick introduction to a few of the most common methods.

Example # 1A

Example # 1B:

In Example # 1, we first create the FP variable, which references the filepath module. Then we create the path variable, which holds the return value of the FP object’s newPath method. And finally, we output the path in the console. Example # 1B shows the terminal output when we use console.log to view the path variable. This path will vary for each user so I simply put “[YOUR LOCAL PATH TO]” for the folder structure that leads up to that file in the github repo that you cloned (see “How to Demo” below).

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: JavaScript/node-js/filepath
  3. Execute the following command in a terminal prompt: node filepath-1.js

Example # 2

Example # 2 demonstrates the list method. The only real difference between this code and Example # 1, is the new variable “files”, which receives the value of the list method, when called on our path variable. The files variable ends up as an array. Each element in the array is an object whose “path” property is a string that points to a file in the current directory.

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: JavaScript/node-js/filepath
  3. Execute the following command in a terminal prompt: node filepath-2.js

Example # 3A

Example # 3B

Example # 3C

Example # 3D

In Example # 3A, we see the recurse method in action. Just as the name implies, the recurse method will recursively list all of the files in the current directory. As a result, if one of those files is a folder, then it will list all of the files in that folder, and so on. This method differs from the previous two examples in that it takes a callback. The callback is a bit like a forEach call; it iterates over all of the files or folders in the path, and calls the callback for each one. Inside of the callback, the path variable is the current path being iterated over.

Example # 3C is the output from the code in Example # 3A.

In Example # 3C, we use the toString() method of the path object so that instead of a bunch of objects that we would need to handle, we just get the values we are after; the string representation of the path to that file or folder.

Example # 3D is the output from the code in Example # 3C.

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: JavaScript/node-js/filepath
  3. Execute the following command in a terminal prompt: node filepath-3.js

Summary

The filepath Node.js module has much more to offer than was demonstrated here. Hopefully, this article has demonstrated how easy it is to get started with filepath.

Helpful Links for the filepath Node.js module

https://www.npmjs.com/package/filepath

http://nodejs.org/api/fs.html

Getting Started with Angular 1.x Custom Directives – Part III – The “restrict” property

Angular

Angular.js LogoLearn how the “restrict” property determines how your Angular.js directive can be invoked

In the second part of this series: Getting Started with Angular.js Custom Directives – Part II – The “replace” property, we learned about how to use the “replace” property when creating a custom Angular.js directive. This determines whether the element that your directive renders will be a child of the element that invoked it, or a complete replacement of that element.

In this article, we will learn about the “restrict” property that, which allows you to specify the ways in which your custom directive can be invoked.

Example # 1:

 

In Example # 1, we have created a custom Angular.js directive named: “uiWidget”. In addition to the “template” and “replace” properties that were discussed in previous articles, we have created a “restrict” property. This property allows you to specify the way in which the directive is invoked. Notice that the value is: “AECM”. These letters stand for:

  • A : Attribute
  • E : Element
  • C : Class
  • M : Comment

You can use any one of the values by itself, or any combination.

Example # 2:

In Example # 2, we have four snippets of HTML. In each case, we demonstrate a different way to invoke our custom Angular.js directive.

First, as an attribute of the HTML element. Notice how the attribute has no value. In our case, the mere presence of the attribute signals to Angular that our custom directive should be invoked.

Second, as an element. Although there is no such thing as a “ui-widget” HTML tag, Angular will recognize this element and invoke our custom directive.

Third, as a CSS class of the element.

Fourth, as a comment. This approach may seem a bit odd, but you can, in fact, trigger your custom Angular.js directive via an HTML comment.

HERE IS THE LINK TO THE WORKING EXAMPLE FOR THIS ARTICLE: http://examples.kevinchisholm.com/angular/directives/basics/html/part-iii.html

Summary

In this article, we learned about the “restrict” property of the object returned by an Angular directive. We discussed the four possible values for this property, and how each case differs.

Getting Started with Angular. 1.x Custom Directives – Part II – The “replace” property

Angular

Angular.js LogoLearn how your Angular.js directive’s “replace” property determines how it is rendered in the DOM

In the first part of this series: “Getting Started with Angular.js Custom Directives – Part I“, we learned the absolute basics of how to create a custom Angular.js directive. In that article, we learned how to create an Angular module, and then call that module’s “directive” method, which takes a function as its second argument. In that function we returned an object with a “template” property, which contained HTML that would become the actual directive, once injected into the DOM.

In this article, we will learn about the “replace” property, which is a member of the object returned by the directive method. This property is a Boolean, so it has two possible values: true and false. When false, your directive’s HTML is injected into the DOM as a sibling of whatever content is already there. When true, your directive completely replaces the element.

Example # 1A:

In Example # 1A, we have HTML that invokes two Angular directives: “ui-widget-replace” and “ui-widget-no-replace”. Both DIVs look are empty and other than the slight variation in the directive name, they look identical.

Example # 1B:

In Example # 1B, we have the JavaScript that defines these two directives. The “uiWidgetNoReplace” directive has its “replace” property set to: “false”. As a result, the widget that is rendered in the DOM is a child element of the element that invoked the widget (i.e. the element with the “ui-widget-no-replace” attribute). The “uiWidgetReplace” directive has its “replace” property set to: “true”. As a result, the widget that is rendered in the DOM REPLACES the element that invoked the widget. In other words: the element with the “ui-widget-no-replace” attribute is replaced by the widget.

Example # 1C:

In Example # 1C, we see the result of our HTML and JavaScript. The first element completely wraps the widget markup, whereas the second element is the widget (i.e. the widget has completely replaced the markup that declared the ui-widget directive).

This result can be verified when you look at the link for the working example. The element with the attribute: “ui-widget-no-replace” has a blue border, and the element with the attribute: “ui-widget-replace” has a red border. Also, you’ll notice that the first widget is has an inner box with a yellow border. This is because there is a parent-child relationship going on here; because the “replace” property’s value is false, the widget is injected into the DOM as a child of the element that invoked the directive. You can view the page source and examine the CSS to see how this style has been applied.

IMPORTANT: Note that we actually create three modules: “myModNoReplace“, “myModReplace“, and “myMod“. The “myMod” module is the main component used in the page, and it declares the modules: “myModNoReplace” and “myModReplace” as dependencies. Module dependencies is a topic that is beyond the scope of this article, and will be covered in a future post. Just know that in order to have multiple modules used in a page, you’ll need to follow this kind of pattern.

HERE IS THE LINK FOR THIS ARTICLE’S WORKING EXAMPLE:

 http://examples.kevinchisholm.com/angular/directives/basics/html/part-ii.html

Summary

In this article, we learned about the “replace” property. This boolean value allows you to determine whether or not the HTML that makes up your custom directive will completely replace the element that declares our directive, or make it a child element.

Getting Started with Angular 1.x Custom Directives – Part I – Introduction

Angular

Angular.js Logo
Learn how to create your own Angular.js directive (it’s much easier than you think!)

It’s hard to imagine any kind of interaction with Angular that does not involve directives. Angular directives allow you to super-charge your HTML, or even create your own tags.

While there is certainly a generous helping of built-in Angular directives, you don’t have to be satisfied with what comes in the box. You can create your own Angular directives. Not only that, but the way your directive is invoked, what it does, and how it works is completely up to you. Because of the kind of abstraction Angular provides, you are limited only by your imagination.

In this article, we will learn how to create our own Angular directive. This is a fairly deep topic, with plenty of detailed discussions to jump into, many of which will be covered in upcoming editions of this series. For this article, we will focus on the core syntax needed to create a directive and have it render something in the DOM.

Example # 1A

In Example # 1A, we create an angular module named: “widgetApp”, and assign it to the variable “myMod”. The syntax is pretty simple: You call the module method of the angular object, passing it two arguments. The first argument is a string, which is the name by which this module will be known by other modules. What is this means is that if this module is to be considered a dependency by one or more other modules, this string is the name by which those modules will call your new module. The second argument is an array. This array can contain one or more dependencies. If your directive will have no dependencies, you can leave this array empty, but it must be there (i.e., you can’t omit the array).

Example # 1B

In Example # 1B, we have created a custom directive by calling the angular.module’s “directive” method. The first argument is a string: the directive’s external name; that is, this is the name by which you will refer to your directive in the DOM.

The second argument is a function. This function is where we will do the work required to create the directive. Notice that the function returns an object. While this object is empty in our example, it is required. So, even though we return an empty object, we are ok (but you must return an object).

While this directive effectively does nothing, the syntax is correct and there will be no errors on page load. But since our directive has no actual functionality, we will need to put a bit more effort into this.

Example # 2

In Example # 2, we have made a small addition to the anonymous function that is passed to the angular.module’s “directive” method: the object that we return now has one property: “template”. This “template” property’s value is a string of HTML that will be injected into the DOM.

This could be considered the bare minimum needed for a directive that actually renders in the DOM: You return an object that has a “template” property. There is still not too much going on here. Our custom “uiWidget” directive simply adds a DIV element to whichever element calls the directive, and the text of that DIV is: “This is a Widget”.

HERE IS THE WORKING CODE EXAMPLE LINK FOR EXAMPLE # 2: http://examples.kevinchisholm.com/angular/directives/basics/html/part-i.html

Hey Kevin, isn’t creating a custom Angular directive supposed to be a bit more exciting than this?

While injecting “This is a Widget” into the DOM is not a particularly eventful outcome here, the areas we covered are important. Any custom directive you create in the future will follow this exact same pattern. The are many more properties that can be members of the return object, and there is a tremendous amount of power and flexibility available when creating a directive. But remember: as you learn more about custom directives in Angular, every concept covered in this article will still apply.

Summary

In this article we learned the absolute basics about how to create a custom Angular.js directive. Although we barely scratched the surface, we did cover the critical details needed in order to create a directive that actually renders somethign in the DOM. We learned how to create an Anuglar module, and then use that module’s “directive” method to create the directive. We also discussed how the directive is created in a function, and how that function must return an object. That object’s “template” property will contain the HTML that will be rendered in the page.

Angular 1.x Basics: Manually Boot-Strapping Your Application (Part II)

Angular

Angular JSOne of the advantages of manually boot-strapping Angular.js is the ability to take care of any setup-tasks that you want completed before the DOM is parsed.

In the previous article: “Angular.js Basics: Manually Boot-Strapping Your Application (Part I)“, we learned how simple it is to manually boot-strap Angular. In that example, our HTML was hard-coded in the page, including the {{myData}} template. We manually boot-strapped Angular by clicking a button, which in-turn, executed our boot-strapping code.

This was fine for a basic proof-of-concept, but having the {{myData}} template render on page load is not acceptable. For this article, our goal will be to inject some HTML into the DOM, and then boot-strap Angular, building upon our code from Part I of this series.

Example # 1:

In Example # 1, we leverage the angular.element() method, passing it a reference to the document object. We then chain the ready() method to the return value of the angular.element() method, passing it an anonymous function. This tells Angular that when the document is in a “ready” state, the anonymous function passed to the .ready() method should be executed.

Example # 2:

In Example # 2, we have added a few things:

1) The base DOM element that will contain HTML, managed by Angular (i.e. DIV#main)

2) A call to the angular.element() method, which sets up an anonymous function that will be called when the document is read

3) The bootAngular() function, which we have re-used from Part I of this series.

HERE IS THE JSFIDDLE LINK FOR EXAMPLE # 2: http://jsfiddle.net/T3jcx/

When you view the JsFiddle.net link for Example # 2, you’ll notice… well you’ll notice nothing! This is because there are no DOM elements for Angular to interact with. Although our code does, in fact, boot-strap Angular, Angular parses the DOM, but finds no “ng” directives or data-bound templates.

Example # 3A:

In Example # 3A, we have a string that contains HTML that will be injected into the page. The actual HTML is virtually identical to the markup from Part I of this series, but instead of hard-coding it in the actual web-page, it is contained in a string, which is a JavaScript variable: “template”.

Example # 3B:

In Example # 3B, we leverage the .run() method of our module. This is a method that we did not create, Angular provides it because our module (“myMod”), was created by Angular. We pass an anonymous function to the .run() method and this function takes the $rootScope object as an argument. A detailed discussion of the $rootScope object is beyond the scope of this article. But, it is helpful to know that it is the top-level container for all data managed by our module.

Inside of the anonymous function passed to the .run() method, we do two things:

1) Set the value of $rootScope.myData

2) Inject our HTML into the DOM

The most important thing to know is that when our module is instantiated, it’s .run() method is executed. So, we have specified what we want done when our module starts, which is to set the value of $rootScope.myData, and inject our HTML into the page.

Example # 4:

In Example # 4, we have the completed code. Comments have been added to help you follow along.

HERE IS THE JSFIDDLE LINK FOR EXAMPLE # 4: http://jsfiddle.net/w6Y3n/

How to Demo This Code:

Although it feels as if the HTML that contains the text box and {{myData}} template render on page load, they do not. Things happen pretty quickly here, but now that we have our completed code, and you have the JsFiddle.net link so that you can see the example code in action, let’s run-down what happens.

1) When the page loads, the BODY tag contains an empty DIV element with the ID: “main”

2) In the SCRIPT block, we create a variable named: “template”, which is a string containing HTML that will be injected into the page

3) We create the function: bootAngular(), which contains the code that boot-straps Angular

4) The angular.element() method is called, and then the ready() method is chained to the return value, and we execute the bootAngular() function as a result

5) Inside the bootAngular() function, we create an Angular module “myApp;” we call the myMod.run() method, which sets the value of $rootScope.myData, and then our HTML is injected into the DOM

6) We call the angular.bootstrap() method, which instantiates the myApp module, telling it to manage the BODY element in our page.

Summary:

In this article, we took a slightly more sophisticated approach to manually boot-strapping Angular. We leveraged the angular.element() method, which allows us to tell Angular to wait until the document is ready before proceeding, by using the .ready() method. We also learned about the [MODULE].fun() method, which provides a way to specify code that will execute when our module is instantiated. In the next article of this series, we will learn how to boot-strap multiple areas of the DOM manually.

 

Angular.js Basics: Manually Boot-Strapping Your Application (Part I)

Angular

Although setting an ng-app directive on the HTML element makes for quick and easy Angular.js boot-strapping, there may be times when you’ll want to initiate that process manually.

In an earlier blog post, we learned that boot-strapping an Angular Application is as simple as setting an ng-app directive on the HTML element, and then adding a script tag that will inject Angular.js into the page. Technically, we can set the ng-app directive on any element in the page, and we can even set it on multiple elements and provide the appropriate values for each directive, so that Angular knows which module will control which portion of the page.

While this kind of declarative architecture is both elegant and efficient, there may be times when you want to boot-strap Angular.js yourself. A common scenario might be one in which you want to have the initial web page render with no application-specific markup, inject the appropriate markup into the page, and then boot the application. This allows you to run any pre-application logic you need, and even decide on which markup to preset first, based on variable such as the URL path, the presence of a cookie, or some other condition.

While some might argue that this could be better handled by Angular Routes and Views, keep in mind that we are talking about tasks we want to run before Angular is even boot-strapped. So, the challenge is: “How can I boot-strap Angular.js manually?”

Fortunately, the process of boot-strapping Angular manually is fairly simple.

The Two Basic Steps Are:

1) Create an Angular module

2) Call the angular.bootstrap method, passing it two arguments: A) An element that the module will manage, and B) The name of the module that will manage that element (and all descendant elements)

Example # 1:

In Example # 1, we have the base HTML for our examples. For the sake of brevity, we are focusing on only the DOM elements that interest us. I’ll assume you understand that there are elements such as DOCTYPE, HTML HEAD and BODY, which make up a basic web page, as well as SCRIPT tags that inject jQuery and Angular, etc.

HERE IS THE JSFIDDLE LINK FOR EXAMPLE # 1: http://jsfiddle.net/mzcxQ/

When you view the JsFiddle.net link for Example # 1, you’ll see that although Angular was injected into the page using a SCRIPT tag in the HEAD section, it has not booted yet. This is evidenced by the fact that the {{myData}} template has not been parsed, and the actual curly braces appear in the page, which is not the desired effect. What we should see is an empty text box, and as you type in the textbox, whatever you have typed appears where the {{myData}} template is.

Example # 2:

In Example # 2, we create a variable named “myMod”. This variable will hold a new Angular module. We create the module by calling the angular.module method, and passing it two arguments:

A) The name of our module: ‘myApp’

B) An empty array

The empty array could be used for dependency injection, which is beyond the scope of this article. We don’t have any dependencies, but even so, the empty array is required.

Example # 3:

In Example # 3, we call the angular.bootstrap method, passing it two arguments:

A) The DOM element which will be managed by a module

B) The name of the module that will manage that element

In this example, we kept it simple and passed a reference to the BODY element, using jQuery. We could have specified the HTML element, or a more deeply-nested element in our page such as $(‘main .appContainer’), for example.

Example # 4:

In Example # 4, we have finally boot-strapped our Angular application. The combination of these two expressions was all that was needed in order to get Angular to start managing our DOM. To help emphasize the demonstration, we will wrap all of our code in a function, and execute that function when the button in our markup is executed.

Example # 5:

 

In Example # 5, we have wrapped all of our code in a function named: “bootAngular()”. We then created a click-event handler for the button in our markup (i.e. #bootAngular). When this button is clicked, the function bootAngular() is executed, and the button is disabled. When the bootAngular() function executes, our Angular boot-strapping code is executed, and Angular is boot-strapped.

HERE IS THE JSFIDDLE LINK FOR EXAMPLE # 5: http://jsfiddle.net/rvM4B/

How to demo this code:

When you view the JsFiddle.net link for Example # 2, you’ll notice that on page load, the {{myData}} template appears in the page. This is not what we want. It happens because while Angular has been injected into the page, it has not been boot-strapped. When you click the button labled: “Boot Angular”, our code executes, Anuglar is boot-strapped, the {{myData}} template disappears, and as we type in the text-box, whatever we type appears where the {{myData}} template was displayed. This is because Angular now manages that portion of the page. It has created a data-binding to the data: “myData” because it parsed the ng-model directive in the HTML, and whenever that data changes, the {{myData}} template is updated accordingly.

Summary:

In this article we learned how to manually boot-strap Angular. We learned how to create an Angular module, and then pass that module to the angular.bootstrap() method. We also learned that we pass a reference to the DOM element which we would like Angular to manage. This simple two-step process is all that is needed to boot-strap Angular. While the example provided is very basic, it illustrates the simplicity with which Angular can be manually boot-strapped.

 

 

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