AMD - Learning JavaScript Design Patterns [Book] - O'Reilly

The overall goal for the Asynchronous Module Definition (AMD) format is to provide a solution for modular JavaScript that developers can use today. It was born out of Dojo’s real world experience using XHR+eval, and proponents of this format wanted to avoid any future solutions suffering from the weaknesses of those in the past.

The AMD module format itself is a proposal for defining modules in which both the module and dependencies can be asynchronously loaded. It has a number of distinct advantages, including being both asynchronous and highly flexible by nature, which removes the tight coupling one might commonly find between code and module identity. Many developers enjoy using it, and one could consider it a reliable stepping stone toward the module system proposed for ES Harmony.

AMD began as a draft specification for a module format on the CommonJS list, but as it wasn’t able to reach full consensus, further development of the format moved to the amdjs group.

Today, it’s embraced by projects including Dojo, MooTools, Firebug, and even jQuery . Although the term CommonJS AMD format has been seen in the wild on occasion, it’s best to refer to it as just AMD or Async Module support, as not all participants on the CommonJS list wished to pursue it.

Note

There was a time when the proposal was referred to as Modules Transport/C, however as the spec wasn’t geared toward transporting existing CommonJS modules, but rather—for defining modules—it made more sense to opt for the AMD naming convention.

Getting Started with Modules

The first two concepts worth noting about AMD are the idea of a define method for facilitating module definition and a require method for handling dependency loading. define is used to define named or unnamed modules based using the following signature:

define(
module_id /*optional*/,
[dependencies] /*optional*/,
definition function /*function for instantiating the module or object*/
);

As we can tell by the inline comments, the module_id is an optional argument that is typically only required when non-AMD concatenation tools are being used (there may be some other edge cases where it’s useful, too). When this argument is left out, we refer to the module as anonymous.

When working with anonymous modules, the idea of a module’s identity is DRY, making it trivial to avoid duplication of filenames and code. Because the code is more portable, it can be easily moved to other locations (or around the filesystem) without needing to alter the code itself or change its module ID. Consider the module_id similar to the concept of folder paths.

Note

Developers can run this same code on multiple environments just by using an AMD optimizer that works with a CommonJS environment such as r.js.    r.js Runs RequireJS in Node and Rhino, and used to run the RequireJS optimizer.

Back to the define signature, the dependencies argument represents an array of dependencies required by the module we are defining, and the third argument (definition function or factory function) is a function that’s executed to instantiate our module. A bare bone module could be defined as follows (Example 11-1):

Example 11-1. Understanding AMD: define()

// A module_id (myModule) is used here for demonstration purposes only
define( "myModule", ["foo", "bar"], // module definition function
// dependencies (foo and bar) are mapped to function parameters
function ( foo, bar ) {
// return a value that defines the module export
// (i.e the functionality we want to expose for consumption) // create your module here
var myModule = {
doStuff:function () {
console.log( "Yay! Stuff" );
}
}; return myModule;
}); // An alternative version could be..
define( "myModule", ["math", "graph"], function ( math, graph ) { // Note that this is a slightly different pattern
// With AMD, it's possible to define modules in a few
// different ways due to it's flexibility with
// certain aspects of the syntax
return {
plot: function( x, y ){
return graph.drawPie( math.randomGrid( x, y ) );
}
};
});

require, on the other hand, is typically used to load code in a top-level JavaScript file or within a module, should we wish to dynamically fetch dependencies. Here is an example of its usage (Example 11-2):

Example 11-2. Understanding AMD: require()

// Consider "foo" and "bar" are two external modules
// In this example, the "exports" from the two modules
// loaded are passed as function arguments to the
// callback (foo and bar) so that they can similarly be accessed require(["foo", "bar"], function ( foo, bar ) {
// rest of your code here
foo.doSomething();
});

The following is an example of a dynamically-loaded dependency (Example 11-3):

Example 11-3. Dynamically-loaded dependencies

define(function ( require ) {
var isReady = false, foobar; // note the inline require within our module definition
require(["foo", "bar"], function ( foo, bar ) {
isReady = true;
foobar = foo() + bar();
}); // we can still return a module
return {
isReady: isReady,
foobar: foobar
};
});

The following is an example of defining an AMD-compatible plug-in (Example 11-4):

Example 11-4. Understanding AMD: plug-ins

// With AMD, it's possible to load in assets of almost any kind
// including text-files and HTML. This enables us to have template
// dependencies which can be used to skin components either on
// page-load or dynamically. define( ["./templates", "text!./template.md","css!./template.css" ], function( templates, template ){
console.log( templates );
// do something with our templates here
} });

Note

Although css! is included for loading CSS dependencies in the above example, it’s important to remember that this approach has some caveats, such as it not being fully possible to establish when the CSS is fully loaded. Depending on how we approach our build process, it may also result in CSS being included as a dependency in the optimized file, so use CSS as a loaded dependency in such cases with caution. If interested in doing the above, we can also explore @VIISON’s RequireJS CSS plug-in further here.

This example could simply be looked at as requirejs(["app/myModule"], function(){}), which indicates the loader’s top level globals are being used.

This is how to kick off top-level loading of modules with different AMD loaders; however, with a define() function, if it’s passed a local require all require([]) examples apply to both types of loader, curl.js and RequireJS (Examples 11-5 and 11-6).

Example 11-5. Loading AMD modules using RequireJS

require(["app/myModule"], 

    function( myModule ){
// start the main module which in-turn
// loads other modules
var module = new myModule();
module.doStuff();
});

Example 11-6. Loading AMD modules using curl.js

curl(["app/myModule.js"], 

    function( myModule ){
// start the main module which in-turn
// loads other modules
var module = new myModule();
module.doStuff(); });

Here is the code for modules with deferred dependencies:

// This could be compatible with jQuery's Deferred implementation,
// futures.js (slightly different syntax) or any one of a number
// of other implementations define(["lib/Deferred"], function( Deferred ){
var defer = new Deferred(); require(["lib/templates/?index.html","lib/data/?stats"],
function( template, data ){
defer.resolve( { template: template, data:data } );
}
);
return defer.promise();
});

AMD Modules with jQuery

Unlike Dojo, jQuery really only comes with one file; however, given the plug-in-based nature of the library, we can demonstrate how straightforward it is to define an AMD module that uses it below.

define(["js/jquery.js","js/jquery.color.js","js/underscore.js"],

    function( $, colorPlugin, _ ){
// Here we've passed in jQuery, the color plugin and Underscore
// None of these will be accessible in the global scope, but we
// can easily reference them below. // Pseudo-randomize an array of colors, selecting the first
// item in the shuffled array
var shuffleColor = _.first( _.shuffle( "#666","#333","#111"] ) ); // Animate the background-color of any elements with the class
// "item" on the page using the shuffled color
$( ".item" ).animate( {"backgroundColor": shuffleColor } ); // What we return can be used by other modules
return {};
});

There is, however, something missing from this example: the concept of registration.

Registering jQuery as an Async-compatible module

One of the key features that landed in jQuery 1.7 was support for registering jQuery as an asynchronous module. There are a number of compatible script loaders (including RequireJS and curl) that are capable of loading modules using an asynchronous module format, and this means fewer hacks are required to get things working.

If a developer wants to use AMD and does not want her jQuery version leaking into the global space, she should call noConflict in their top level module that uses jQuery. In addition, since multiple versions of jQuery can be on a page, there are special considerations that an AMD loader must account for, and so jQuery only registers with AMD loaders that have recognized these concerns, which are indicated by the loader specifying define.amd.jQuery. RequireJS and curl are two loaders that do so.

The named AMD provides a safety blanket of being both robust and safe for most use cases.

// Account for the existence of more than one global
// instances of jQuery in the document, cater for testing
// .noConflict() var jQuery = this.jQuery || "jQuery",
$ = this.$ || "$",
originaljQuery = jQuery,
original$ = $; define(["jquery"] , function ( $ ) {
$( ".items" ).css( "background","green" );
return function () {};
});

Why AMD is a better choice for writing modular JavaScript

We have now reviewed several code samples taking us through what AMD is capable of. It certainly appears to give us more than just a typical Module pattern, but why is it a better choice for modular application development?

  • Provides a clear proposal for how to approach defining flexible modules.

  • Significantly cleaner than the present global namespace and <script> tag solutions many of us rely on. There’s a clean way to declare standalone modules and dependencies they may have.

  • Module definitions are encapsulated, helping us to avoid pollution of the global namespace.

  • Arguably works better than some alternative solutions (e.g., CommonJS, which we’ll be looking at shortly). It doesn’t have issues with cross-domain, local, or debugging and doesn’t rely on server-side tools to be used. Most AMD loaders support loading modules in the browser without a build process.

  • Provides a “transport” approach for including multiple modules in a single file. Other approaches like CommonJS have yet to agree on a transport format.

  • It’s possible to lazy load scripts if this is needed.

Note

Many of the above could be said about YUI’s module loading strategy as well.

AMD - Learning JavaScript Design Patterns [Book] - O'Reilly的更多相关文章

  1. Learning JavaScript Design Patterns The Module Pattern

    The Module Pattern Modules Modules are an integral piece of any robust application's architecture an ...

  2. Learning JavaScript Design Patterns The Observer Pattern

    The Observer Pattern The Observer is a design pattern where an object (known as a subject) maintains ...

  3. Learning JavaScript Design Patterns The Singleton Pattern

    The Singleton Pattern The Singleton pattern is thus known because it restricts instantiation of a cl ...

  4. Learning JavaScript Design Patterns The Constructor Pattern

    In classical object-oriented programming languages, a constructor is a special method used to initia ...

  5. use getters and setters Learning PHP Design Patterns

    w Learning PHP Design Patterns Much of what passes as OOP misuses getters and setters, and making ac ...

  6. Learning PHP Design Patterns

    Learning PHP Design Patterns CHAPTER 1 Algorithms handle speed of operations, and design patterns ha ...

  7. JavaScript Design Patterns: Mediator

    The Mediator Design Pattern The Mediator is a behavioral design pattern in which objects, instead of ...

  8. Javascript Design Patterns - Js Class

    JavaScript is a class-less language, however classes can be simulated using functions. eg: // A car ...

  9. .Learning.Python.Design.Patterns.2nd.Edition之单实例模式

    可以慢慢理解.. 对照JAVA class Singleton(object): def __new__(cls): if not hasattr(cls, 'instance'): cls.inst ...

随机推荐

  1. C++中的class和struct区别

    1,经过不停的改进,结构体 struct 变得原来越不像它在 C 语言中的样子了: 1,struct 在 C 语言中仅为了定义一个变量的集合,仅此而已,不能定义函数: 2,struct 在 C++ 中 ...

  2. mybatis oracle 批量新增

    假定场景:批量导入用户信息 一般批量新增使用 SELECT … INSERT INTO 和 INSERT INTO … SELECT 我们这次使用第二种 一.先建一张用户信息表模拟批量导入用户信息 c ...

  3. 安装RF

    pip install robotframework wxPython pip install robotframework-ride pip install --pre --upgrade robo ...

  4. java中遍历实体类属性和类型,属性值

    public static void testReflect(Object model) throws NoSuchMethodException, IllegalAccessException, I ...

  5. php 多维数组转一维数组

    1.巧用 RecursiveIteratorIterator $k_arrays_arrays_tmp = iterator_to_array(new RecursiveIteratorIterato ...

  6. MongoDB入门_MongoDB特色

    1. sql数据库与nosql数据库对比 nosql不支持实时一致性转而支持数据的最终一致性,数据有一定的延迟 redis数据库支持部分事物,而mongodb不支持事物 nosql数据库没有多表联查功 ...

  7. CentOS7搭建FastDFS V5.11分布式文件系统及Java整合详细过程

    1.1 FastDFS的应用场景 FastDFS是为互联网应用量身定做的一套分布式文件存储系统,非常适合用来存储用户图片.视频.文档等文件.对于互联网应用,和其他分布式文件系统相比,优势非常明显.其中 ...

  8. Codeforces 960 二进制构造子序列 完全二叉树shift模拟 主席树/MAP DP

    A #include <bits/stdc++.h> #define PI acos(-1.0) #define mem(a,b) memset((a),b,sizeof(a)) #def ...

  9. Python核心技术与实战——八|匿名函数

    今天我们来学习一下匿名函数.在学习了上一节的自定义函数后,是时候了解一下匿名函数了.他们往往非常简短,就一行,而且有个关键字:lambda.这就是弥明函数. 一.匿名函数基础 匿名函数的基本格式是这样 ...

  10. CSP-J&S 游记以及总结

    前言 以前的比赛没有写什么总结,都只注重结果,没有注重过程,不知道如何才能在比赛中拿到高分,因此这次CSP才会考得一塌糊涂. 从此吸取教训,每场比赛都要总结经验,每场比赛都要尽全力考,每个题目都要尽全 ...