of Asynchronous Module Definition (AMD) presents Dylan Schiemann, CEO, SitePen James Thomas, UI Technical Lead, IBM IBM Impact 2012 Conference, TDW-2286 Tuesday, 8 May 2012
asynchronous module loading and callback management Allows for loading of non-AMD modules, sometimes using plugins (HTML templates, JSON/config files, basic ".js" files) dojo/domReady! dojo/text! Works via script tag injection (or XHR) and onload events Tuesday, 8 May 2012
We’re simply injecting <script> tags! Prevents the need for globals Provides excellent encapsulation Mix and match code from different projects Load only what you need, expose only what you should! Loads modules only once, caches them Simple API: define and require Tuesday, 8 May 2012
"Base-less" Dojo Only using the parts of Dojo you really need, on a much more granular level Dojo 1.7 AMD loader <4K gzip/minified Asynchronous Module Definition (AMD) A grassroots standard for interoperable code modules Client and Server Plugin framework for additional extensibility Default module system for Dojo 1.7+ Tuesday, 8 May 2012
build with dependency resolution, AMD & has.js optimized builds. • All from one place with full licensing and support. Dojo Base Dijit (View) dojox Grid dojo/store (Model) Dojo Nano Tuesday, 8 May 2012
JavaScript source code AMD creates two global functions, require and define Replaces dojo.provide, dojo.require, dojo.requireIf, dojo.requireAfterIf, dojo.platformRequire, & dojo.requireLocalization Modules are grouped into collections called packages Examples: dojo, dijit, and dojox Modules normally have a 1:1 mapping to files Except when production-optimized through a build Tuesday, 8 May 2012
modules into optimized resources to improve production performance Dojo builder (plus Dojo ShrinkSafe or Closure Compiler) Uglify RequireJS - r.js Zazl Tuesday, 8 May 2012
path fragments; e.g. dijit/form/Button Work a lot like paths relative path fragments like "./" and "../" can be used to refer to other modules within the same package Necessary for fully portable packages Can be aliased/overridden to point to different code Tuesday, 8 May 2012
arguments: configuration: Optional, a configuration object for the loader dependencies: Optional, an array of strings as a list of module identifiers to load before calling the callback callback: Optional, a function to call when dependencies are loaded What does it do? Reconfigures the loader at runtime Loads modules and executes an optional callback when they are loaded, passing loaded modules into the Tuesday, 8 May 2012
the configuration object here, just an array of requirements and // a callback. dojo/domReady! is a plug-in that we will explain in a moment. require(["dojo/dom-construct", "dojo/domReady!"], function(domConstruct){ var newButton = domConstruct.create("button", {innerHTML: "foo"}); domConstruct.place(newButton, document.body, "last"); }); // The same code in the legacy system // dojo.require("dojo/dom"); //this module was included by default dojo.ready(function(){ var newButton = dojo.create("button", {innerHTML: "foo"}); dojo.place(newButton, document.body, "last"); }) require() Tuesday, 8 May 2012
define function Code contained within is not resolved until they are required (lazy instantiation) Factory is only called once; the return value is cached by the loader and shared between all modules Special plugin modules exist to extend loader functionality Tuesday, 8 May 2012
arguments: moduleId: Optional, a string to explicitly identify the module dependencies: Optional, an array of strings as a list of module identifiers to load before calling the factory factory: The value of the module, or a function that returns the value of the module What does it do? Defines the value of a module Typically the moduleId is reserved for the build system - don't explicitly identify your modules! Tuesday, 8 May 2012
with AMD define( ["dojo/_base/declare", "dijit/_WidgetBase", "dijit/_TemplatedMixin", "dojo/text!./templates/TemplatedWidget.html"], function(declare, _WidgetBase, _TemplatedMixin, template){ return declare([_WidgetBase, _TemplatedMixin], { templateString: template }); } ); // Note how the dependencies map into the function call! Creating a widget with define + declare Tuesday, 8 May 2012
as a plain object define({ enabled: true, delay: 500 }); The value given for a module can also be just a plain object Modules defined as plain objects typically have no dependencies since there is no factory function that can use the references to those dependencies define() Tuesday, 8 May 2012
dojo.provide AMD is less verbose AMD is fully self-encapsulated No references to global variables or the module's own package name Faster scope lookups Better minification Impossible to forget a dependency and still have working code Zero global namespace pollution Completely portable Tuesday, 8 May 2012
for conditional requirements: Dependencies that cannot be determined until runtime dojox/gfx uses this concept to decide which rendering engine to use (VML, SVG, canvas, etc) Modules that you only want to load when a certain condition occurs (configuration, event, etc) Tuesday, 8 May 2012
sensitive require Resolves relative module ids with respect to the depending module; just like relative module ids are resolved in the module's dependency list Relative module lookups don't work with global require Tuesday, 8 May 2012
is the initial value of the module Useful for managing circular dependencies exports is the implicitly returned object that represents the value of the module Tuesday, 8 May 2012
similar define(["exports"], function(exports) { export.foo = "Hi"; }); define(function() { return { foo: "Hi" }; }); define(function (require, exports, module) { ... }); // will cause the factory to be scanned for require('dep'); calls and will pass require, exports and module to the factory. define([], function () { ... }); //will not scan the factory and will not pass anything to the factory. exports Tuesday, 8 May 2012
never be specified explicitly in a define call (it is for build tools) dojo.declare should never specify the name of the class being declared (unless creating declarative widgets) If you want to create private classes, remember you can just assign the return value of dojo.declare to a local variable Dependencies to modules within a package should always use relative module identifiers Tuesday, 8 May 2012
variables is verboten There are some areas where this is still required (some Dijits break the rules and declare multiple classes), but should improve beyond 1.7 This is especially relevant if you are defining a module without a factory function; if you have any direct dependencies, you should be using a factory function Conditional requires with relative module identifiers must use a context-sensitive require Tuesday, 8 May 2012
you share portable modules with the community? Use or extend CJS module template to define your module Fill out package.json Submit your package! http:// packages.dojofoundation.org/submit.html How do you share portable modules with the community? If you are defining a module without a factory function and you have any direct dependencies, you should be using a factory function Conditional requires with relative module identifiers must use a context-sensitive require Tuesday, 8 May 2012
in lots of useful ways Common plugins available with most loaders are "text", "i18n", and "domReady" Plugin dependencies are identified by the exclamation point in the module identifier: "dojo/ text!", "dojo/i18n!", "dojo/domReady!" Data to the left of the "!" identifies the plugin to load; data to the right of the "!" is passed to the plugin for processing Tuesday, 8 May 2012
(quotes) { // quotes will simply be the content of the file, // so we'll split on newlines var quotes = quotes.split("\n"); // Write out a random quote to the console console.log(quotes[Math.floor(quotes.length * Math.random ())]); }); Loads string from file (XHR if not built-in, cross-domain care is needed) Replaces dojo.cache Used mostly for loading template strings, but can load any string Build system interns strings loaded using dojo/text, just like dojo.cache Compatible with RequireJS's text plugin dojo/text Tuesday, 8 May 2012
() { console.log("DOM is ready!"); }); require(["dojo/ready", "dojo/parser", "dijit/registry", "dijit/Dialog"], function (ready, parser, registry){ ready(function(){ // This won't run until the DOM has loaded, the parser has run, and other // modules like dijit/hccss have also loaded. var dialog = registry.byId("myDialog"); ... }); }); Ensures the module does not resolve until the DOM is ready Replaces dojo.ready Compatible with RequireJS's domReady plugin dojo/domReady and dojo/ready Tuesday, 8 May 2012
function (eventHandlers) { // Do something with eventHandlers }); Allows modules to be conditionally loaded, using has.js features Replaces dojo.requireIf dojo/has Tuesday, 8 May 2012
module identifiers can be used to load arbitrary, non-AMD scripts as dependencies, in which case the module's returned value will be undefined: Any identifier starting with "/" Any identifier starting with a protocol (e.g. "http:", "https:") Any identifier ending with ".js" curl.js and perhaps others use js! prefix (e.g. "js!https://ajax.googleapis.com/ajax/libs/mootools/1.4.1/ mootools-yui-compressed.js Tuesday, 8 May 2012
defines the base path for all modules; can be relative or absolute Relative values are relative to the HTML file in browsers and relative to the current working directory on servers packages: defines all of the packages registered for the application name is the name of the package location is the location of the package; relative paths are relative to baseUrl main is the name of the module that will be loaded if someone tries to require the package itself; this defaults to "main" (e.g. requiring "foo" will load the "foo/main" module) Tuesday, 8 May 2012
Note that packageMap was recently renamed map in the AMD spec. { name: "my", location: "my", packageMap: { array: 'dojo/_base/array', xhr: 'dojo/ _base/xhr', ...} } // require or define that uses the map define(['array', 'xhr', 'query'], function (array, xhr, query) { }); A map that allows package names to be aliased to other locations for this particular package only Use two packages with the same name (e.g. multiple versions) at the same time, as long as the package authors followed best practices and did not use an explicit moduleId in their define calls Simply install the two packages to two different directories and then define each package with a unique name in the packages array. Mapping Packages Tuesday, 8 May 2012
starts after css is loaded }); A framework for shimming (or polyfilling) and extending CSS, to efficiently support various plugins for additional CSS functionality and backwards compatibility of newer features. A CSS loader plugin for AMD loaders xstyle Tuesday, 8 May 2012
of this we layer our JavaScript application. Each page has a block of inline JavaScript that checks the capabilities of the browser before deciding whether to kick start the enhanced experience. Progressive enhancement, really, at heart. The JavaScript will include curl.js into the page and then AMD modules will load additional functionality into the page (our drop-down section navigation for example). The USP of this UI is that it provide a news service that tailored to new hardware/software." Tuesday, 8 May 2012
application Shows off famous landmarks (Eiffel Tower, Golden Gate Bridge, etc.) ESRI map API (using Dojo 1.6, pre-AMD) Flickr image API Wikipedia content Work well on desktop, phones, and tablets WebKit, Firefox, iOS, and Android were the initial targets Tuesday, 8 May 2012
// Exposes the Dojo 1.6-based Esri API for AMD apps as an AMD loader plugin. var esriApi; return { load: function(moduleId, require, callback){ if(esriApi){ callback(esriApi); return; } // The Esri API *requires* the older djConfig variable name // for its configuration var oldDjConfig = window.djConfig; window.djConfig = { scopeMap: [ // Lowercase scope map names are used because of some // peculiar behaviour observed during testing where JSONP // requests would be sometimes returned with lowercase // callback names even though the original call used // mixed-case names [ "dojo", "esridojo" ], [ "dijit", "esridijit" ], [ "dojox", "esridojox" ] ] }; // ... esriApi.js Tuesday, 8 May 2012
to mix and match to create your app Separate data from UI logic simple and seamlessly Modular enough for very simple projects, flexible and consistent enough to handle the most challenging, feature-rich web apps Tuesday, 8 May 2012
1.8+ API Clean-up, Further Split of Features Compose (improved declare), xstyle, put-selector, Dijit/ Widget Remove weight of deprecated APIs Tighter dependencies DojoX completely moved to Dojo Foundation packages Releases Independent releases of packages, roll out package release sets Support major HTML5, mobile, modern browser features Web Builder and Dojo Foundation Packages Tuesday, 8 May 2012