# Preface

Users now demand web applications that look and feel like those of the desktop. Home computers have long since become ubiquitous, web browsers are the enabling platform, and virtually everyone on the planet is a potential end user. Software developers are spending more time than ever getting their applications into the browser for a potential audience of millions—many of them trying to grab a handful of the multibillion dollar advertising wave, while others are capitalizing on the sheer elegance and convenience of an application that is impressive enough that people will be willing to pay for access to it.

Of course, just because the web browser is the enabling platform does not mean that it is the ideal platform—at least not in its current manifestation. Corporate politics, less than uniform implementations of the various specifications for web browser technologies, and a curious evolution of protocols and standards over almost two decades have made deploying an application in the browser a lot more difficult than anyone might have ever predicted.

But in a world where necessity breeds imagination and innovation, there is always hope.

Fortunately, the rich and powerful functionality JavaScript provides makes it possible to manipulate, customize, and augment a web page on the fly, and in doing so, makes it possible to provide a layer of insulation between the developer and the bare metal of the web browsers—even all of them at the same time.

This book is about Dojo, a JavaScript toolkit that provides that layer of insulation between you and the hard knocks of browser inconsistencies by leveraging JavaScript and other web technologies for all that they're worth—not by attempting to build a brittle, superficial layer to reimplement or work around them. Dojo makes a great addition to a project that's already using YUI![1] or even a server side framework that might benefit from offloading some of the work over to the client.

Dojo packs the standard JavaScript library you've always wanted, the collection of drop-in replacements for the customized HTML controls and CSS layout hacks you've implemented again and again, and the build tools and unit tests that would have been so handy when it came time for migrating to production. Dojo isn't just a JavaScript toolkit, Dojo is the JavaScript toolkit—and right now is a great time to learn how to use it to make your life easier and the experience of your end users everything that it possibly can be. Dojo is revolutionizing web development, and gaining momentum fast.

Whatever web development project may be on your horizon, rest assured that Dojo can help you realize it quickly and with minimal boilerplate so that you're left with the cleanest, most maintainable implementation possible. My sincere hope is that this book relates Dojo's story so effectively that you'll spend minimal time scrambling around for answers and be able to fully concentrate on engaging the challenging (and far more interesting) problems that you've set out to solve.

## Why Dojo?

Undoubtedly, there is a swatch of JavaScript toolkits available today, so you might already be wondering what Dojo provides that you can't get somewhere else. Keeping in mind that the very nature of a toolkit or library being built upon a completely interpreted language makes it theoretically possible for any other toolkit to do the very same things, it's not so much what can Dojo do that other can't do; rather, it's more about the effectiveness of getting work done along with the community, philosophy, and licensing aspects that surround it.

You might think of it like this: it's theoretically possible to build a house using only a hammer, a shovel, a saw, and a lot of nails—but at what expense? Clearly, some heavy machinery and some carpenters to support you along the way would be a tremendous boon. The situation with Dojo is quite similar. The following list attempts to highlight (in no particular order) some of the places where Dojo really shines and differentiates itself:

Community

Although it could be considered a nontechnical issue, Dojo's open community is one of its top strengths. The Dojo Foundation, a nonprofit organization set up for the purpose of providing a vendor-neutral guardian of intellectual property, backs the toolkit (and other interesting projects such as Cometd,[2] DWR,[3] and OpenRecord[4]), and is sponsored and supported by IBM, AOL, Sun, OpenLaszlo, Nexaweb, SitePen, BEA, Renkoo, and a slew of the greatest DHTML hackers in the world. If that doesn't tell you that it has good friends backing it, then what possibly could?

As a liberally licensed open source project with extremely low barriers to entry, your voice will be heard if you want it to be heard. If you pop into the IRC chat room #dojo on freenode.net and start talking, there's virtually no chance that you won't be heard by a committer or significant contributor to the project. Additionally, weekly IRC meetings are currently held on #dojo-meeting each Wednesday from 3 to 6 P.M. (PST), and you're more than welcome to pop in and eavesdrop or participate in the official meetings where both strategic and tactical issues are routinely discussed.

Knowing there's transparency in how Dojo is steered strategically and developed tactically is very compelling. As other JavaScript toolkits and libraries become increasingly commoditized, the Dojo community really stands out as different. The organizations and individuals who make up the team of committers (not to mention the thousands of individual developers out there building real web sites and applications) all give Dojo a particular character and grounding for success.

Liberal (and clean) licensing

Dojo is open source software that is liberally licensed under the terms of either the modified Berkeley Software Distribution (BSD) license or the Academic Free License (AFL) version 2.1. Except as noted in a few per-module license files, you get to choose the license you want to adopt for your specific work. All external contributions are required to be compatible with the BSD or AFL licenses, and all contributors must sign a Contributor License Agreement (CLA) that ensures the Dojo Foundation has clear title to all contributions—thereby protecting all users of the toolkit from intellectual licensing conundrums. The benefit of clean licensing is markedly not the case with several other popular JavaScript toolkits (that shall be left unnamed).

While some toolkits tackle specific pieces of a problem space, Dojo provides an end-to-end solution for development in the browser. Everything from standard library utilities to turnkey widgets to build tools and a testing framework—it's all in there, so you seldom have to look elsewhere. But don't let the breadth fool you into thinking that there is code bloat, because the build tools allow you to produce custom versions of the toolkit that can be as streamlined as your application permits.

While it is often the case that breadth hampers depth, it's not what happens with Dojo at all. Even inside of Base, the tiny kernel that provides the foundation for the rest of the toolkit, you have more functionality than you can shake a stick at—facilities for universally querying the DOM via CSS3 selectors, AJAX utilities, event normalization amongst various browsers—and then some. That doesn't even begin to touch of the rich library of application, form, and layout widgets, or the build tools.

Although the breadth and depth of Dojo produces a lot of complexity, the infrastructure is painstakingly reviewed on a continual basis by the some of the best web hackers in the world for high quality coding standards, consistent naming conventions, performance, maintainability, and overall ease of use for the application developer. Rest assured that you will be able to create a great user experience with Dojo.

Portability

While the JavaScript language is dynamic, powerful, and extremely expressive, there are still myriad issues that come up routinely that amount to fairly mundane engineering efforts. It's quite instructive to go through the motions that solve a central algorithmic problem or engineering conundrum, but at the end of the day, any code that you develop is code that you have to maintain, update, debug, and document.

As if those aren't enough good reasons, the motivation for having a JavaScript standard library may be especially compelling given the existing state of compatibility amongst browsers for various feature sets. While attempting to develop a feature that works uniformly across a set of modern browsers may not always be rocket science, it can be painfully tedious work that can demoralize even the most seasoned professionals.

The bottom line is that it's almost a certainty that as an application developer, you aren't going to be receiving any return on investment (or having very much fun) by jumping through all of those hoops. Instead, pick up production quality code that a community of other developers has developed, debugged, and tested—and then consider contributing back. Hopefully, that "giving back" part will come naturally enough once you've saved enough time and money by way of community-supported, open source software.

Pragmatic philosophy

Dojo embraces JavaScript for what it is instead of treating it like it's something that's broken and thereby trying to create a brittle, artificial layer on top of it that almost redefines it. While Dojo exposes tremendous functionality that protects you from the bare metal of the browser and does many things like normalize browser events behind the scenes so that you don't even have to think twice about them, it never attempts to reinvent JavaScript. For example, you won't find Dojo-specific functions for operations like deleting DOM nodes or walking the DOM tree because operations like childNodes, firstChild, lastChild, and removeChild work just fine across all browsers. However, whenever there are known inconsistencies, Dojo steps in to provide you with the tools you need to write portable code.

For that matter, Dojo doesn't attempt to lockout or constrain your use of other JavaScript libraries; it is not uncommon to see it used side-by-side with another technology like DWR or YUI!. And of course, as a client side technology, you are obviously free to use whatever technologies you'd like on the server since Dojo is server-agnostic.

A comprehensive survey of all of the popular JavaScript toolkits would reveal that they all have considerable overlap by virtue of being popular in the first place. So, when it comes time to make a decision about which toolkit or collection of toolkits is right for you, it is worth the time to really ponder the value of community, transparency, licensing, and the philosophy governing the technology in which you are about to invest time and possibly even money. Namely, you want to have support (community and documentation) when you need it, you don't want to invest in a project that's too brittle to be maintained or about to tank, and you want minimize your time working to plug holes that some other toolkit has already plugged.

## What's in This Book

Part I of this book is very much a standard library reference that exposes you to the various nooks and crannies of Base and Core, the parts of the toolkit that comprise a JavaScript standard library. Base comes across the wire[5] at less than 30KB, and is feverishly optimized for speed, size, and utility. Packing rich functionality as diverse as AJAX calls, DOM querying based on CSS selector syntax, standardized event propagation, and functional programming utilities like map and filter, you'll quickly wonder how you ever got by without it. Core includes lots of additional features for operations like animations and drag-and-drop; while they are incredibly useful, they just aren't as common to all use cases as the machinery in Base.

One caveat about Part I of this book is that it defers a full-blown discussion of the parser until Chapter 11, when Dijit is introduced, because the most common use case of the parser is for parsing widgets. The parser is briefly mentioned in a Chapter 7 sidebar, though, because it is quite helpful for conveniently setting up drag-and-drop.

Part I includes the following chapters:

Chapter 1

Provides a quick introduction to the toolkit including topics such as Dojo's architecture, how to get and install Dojo, how to get Dojo into a web page, and some sections that provide some examples so that you can see Dojo in action.

Chapter 2

Provides an extensive overview of commonly used utility functions that are extremely common and useful for any web application. Most of these functions are designed to smooth out browser incompatibilities, plug holes where JavaScript or DOM implementations came up a bit short, and otherwise reduce the boilerplate you have to write to get some work done.

Chapter 3

Introduces constructs for managing communication within the page. The two primary paradigms discussed involve directly attaching to a specific event that happens, whether in the DOM, on an Object, or a standalone function and the publish/subscribe idiom that involves broadcasting a topic and allowing any arbitrary subscriber to receive and respond as needed.

Chapter 4

Provides a quick overview of AJAX and the toolkit's machinery for communicating with the server via the XMLHttpRequest Object. Deferreds are also discussed, which provide a uniform layer for handling asynchronous events; you might think of Deferreds as almost providing the illusion of having a thread available even though you cannot program threads in JavaScript. Other core facilities such as cross-domain JSON, Remote Procedure Calls, and IFRAME transports are discussed.

Chapter 5

Introduces the toolkit's mechanism for universally querying the DOM using CSS selector syntax, processing the lists of nodes that are returned using convenient built-in functions that allow arbitrary events chains to be built up, and an idiom for separating the behavior of DOM nodes from specific actions defined in HTML markup.

Chapter 6

Provides a quick overview and examples for internationalizing a web application using the toolkit's utilities; also includes an overview of the various constructs that are available for manipulating inherently international concepts such as dates, time, currency, and number formatting.

Chapter 7

Includes a fairly standalone tutorial on how Dojo makes adding drag-and-drop to an application a breeze.

Chapter 8

Provides a fairly standalone tutorial on Dojo's built-in machinery for animating arbitrary CSS properties via a variety of effects such as wipes, slides, and fades. Utilities for blending and manipulating colors are also included.

Chapter 9

Provides a discussion of Dojo's data abstraction infrastructure, which provides a mediating layer between application logic and specific backend data formats, whether they be an open standard or a closed proprietary source.

Chapter 10

Ramps up for Part II on Dijit by introducing machinery for mimicking class-based object-oriented programming with Dojo, which Dijit uses fairly extensively.

Part II systematically explores the rest of the toolkit, including complete coverage of Dijit, the rich layer of drop-in replacements for all of those customized HTML controls that have been written (and rewritten) so many times. Dijit is designed so that it can be used in the markup with little to no programming required, and you'll find that it's possible to build fantastic-looking web pages with a fraction of the effort since they already look and behave much like user interface controls from desktop applications.

Part II concludes with a discussion of the build system and unit testing framework provided by Util. The build system includes a highly configurable entry point to ShinkSafe, a tool that leverages the Rhino JavaScript engine to compress your code—often by a third or more. DOH stands for the Dojo Objective Harness (and is a pun on Homer Simpson's famous "D'oh!" expletive) and provides a standalone system for unit testing your JavaScript code.

Part II includes the following chapters:

Chapter 11

Introduces Dijit, discusses various issues such as design philosophy, accessibility, the parser (technically a Core facility, but with the most common use case of parsing a page that contains dijits), and patterns for using dijits. The chapter ends with an overview of each major Dijit subproject.

Chapter 12

Digs deep into how a dijit is laid out on disk as well as how its lifecycle works once it's been instantiated and in memory. Provides a number of short examples that accentuate the finer points of the lifecycle. Understanding the dijit lifecycle is essential for the chapters that follow.

Chapter 13

Provides a quick review of normal HTML forms and then jumps right into a thorough survey of the form widgets, which are by far the most inheritance-intensive collection available. The form widgets are drop-in replacements for all of the common form elements that are used in virtually any web design; assortments of commonly used buttons, specialized text boxes, and sliders are a few of the topics covered. Additional derived elements such as drop-down combo boxes that have been implemented and reimplemented far too many times by now are also included.

Chapter 14

Introduces the layout widgets, a collection of widgets that provide the skeleton for complex layouts that often involves tricky and tedious CSS, swapping in and out tiles that go from being hidden to visible based on the application's state, tabbed layouts, and more.

Chapter 15

Covers the remaining widgets in the toolkit, which loosely correspond to common application controls such as tooltips, modal dialogs, menus, trees, and rich text editors.

Chapter 16

Wraps up the book with some of the most commonly overlooked yet important topics for deploying an application; includes an extensive discussion of the build tools that trivialize the effort entailed in compressing, minifying, and consolidating JavaScript to minimize file size and HTTP latency incurred, a unit testing framework, and other production considerations that help to give your app that last bit of pizzazz.

There are two supplemental appendixes to the book: a concise survey of DojoX, a collection of specialized and experimental extensions, and a Firebug tutorial. While DojoX is an absolute treasure chest of widgets and modules for anything from charting to cryptography to the much acclaimed and highly flexible grid widget, there are fewer guarantees about stability or API consistency for DojoX subprojects than there are for Base, Core, and Dijit; thorough coverage on DojoX could easily span multiple volumes of its own.

The other appendix provides a handy Firebug tutorial that gets you up to speed with all of its great features that will save you time when it becomes necessary to debug or quickly explore new ideas through its command line style interface. If you haven't heard of Firebug, it's a fantastic Firefox add-on that allows you to literally deconstruct every facet of a page—anything from inspecting and manipulating style of DOM nodes to monitoring the network activity to using a command-line interface for executing JavaScript.

## What's Not in This Book

While this book necessarily attempts to provide the same kind of depth and breadth of Dojo itself, there were a few topics that just couldn't quite be squeezed into this edition:

Web development 101

While this book provides in depth coverage of Dojo, it doesn't provide a complete web development tutorial that formally introduces elementary constructs such as HTML, JavaScript, and CSS from scratch.

Redundant API documentation

The vast majority[6] of Dojo's API is definitively explained in this book and is generally captured into tables that are easy to reference. Because there's so much breadth to Dojo, it seemed especially helpful to make sure you get exposed to as much of it as possible so that you'll know what's available when the need arises. Dojo is a fluid project, however, so you'll always want to double-check the online documentation at http://api.dojotoolkit.org for the most comprehensive authority. Unlike programming languages and more rigid application frameworks, Dojo is a fluid project with a thriving community, so it is not unlikely that the API may be enhanced for your benefit as new versions are released. But do know that the project is committed to not breaking the 1.x API until at least version 2.0, so in general, any API covered in this book will be perfectly valid for quite some time. Even then, the parts of the API that do change will be well documented ahead of time.

Nonbrowser host environments

This book also doesn't elaborate or provide examples on how you can use Dojo outside of the typical browser environment (such as in a Rhino or Adobe AIR environment) or include coverage on how you can use Dojo in combination with other client-side frameworks such as DWR, YUI!, or Domino.

## Open Source Software Is Fluid

Dojo is open source software with a thriving community, and as such, may add new features at any time. This book is written to be completely up-to-date as of Dojo version 1.1, but clearly, future versions could add more functionality. To be sure that you're as current as possible with the latest Dojo happenings, be sure to read the release notes for versions more recent than 1.1.

Also, be advised that Dojo's API is currently frozen until version 2.0, so all of the examples and information in this book should be correct through the various minor releases along the way. Even if you're reading this book and version 2.0 has already been released, the code examples should still work as the unofficial deprecation policy is that whatever is deprecated in a major release may not be axed until the next major release. In other words, anything that is deprecated in version 1.x will survive through until at least the 2.0 release, and maybe longer.

This book assumes that you've done at least a mild amount of web development with client-side technologies such as HTML, JavaScript, and CSS. You by no means, however, need to be an expert in any of these skills and you really don't need to know anything at all about what happens on a web server because Dojo is a client-side technology; merely having dabbled with them enough to know what they are and how they are used is more than enough.

If you are an existing web developer or even a hobbyist who is able to construct a very simple web page and apply a dab of JavaScript and CSS to liven it up a bit, then you should definitely keep reading. If you haven't even heard of HTML, JavaScript, or CSS, and have never done so much as written a line of code, then you might want to consider picking up a good introduction on web development as a supplement to this book.

### Development Tools

With regard to development tools, although you could use your favorite text editor and any web browser to do some effective development with Dojo, this book makes frequent references to Firefox and the wonderful Firebug add-on that you can use to debug and deconstruct web pages as well as tinker around with JavaScript in its console. Although you could use Firebug Lite with another browser like Internet Explorer, the full version of Firebug is vastly superior and you won't be disappointed by it. (In general, a practice that's commonly accepted is to develop with Firefox using Firebug, but test frequently with IE.) You can get Firefox and Firebug from http://getfirefox.com and http://getfirebug.com, respectively.

Two other tools you may want to consider for Firefox are Chris Pederick's Web Developer Toolbar, available at http://chrispederick.com/work/web-developer/, which provides some additional tools that are useful during development, and the Clear Cache Button Firefox add-on, available at https://addons.mozilla.org/en-US/firefox/addon/1801, which is a button for your toolbar that you can use to quickly clear your cache. Occasionally, it can be the case that your browser may "act up" and serve you stale content; clearing the cache sometimes helps.

### Essential Working Knowledge

Closures, context, and anonymous functions are some of the most important fundamental concepts in JavaScript, and because mastery of the toolkit involves more than a casual understanding of these topics, this section is worth a careful read. Even though it may sound like advanced material, these concepts are essential to mastering the JavaScript language and really understanding some of the underlying design within the toolkit. You could try and pick up this knowledge as you go along, but if you spend a little bit of time up front, you'll find that many selections from the ensuing chapters are considerably easier to understand.

#### Closures

A closure is essentially the coupling of data elements and the scope that contains (or encloses) that data. Although typical situations involving a single global scope that contains some functions are fairly straightforward, nested functions have the ability to really change things up. To illustrate, consider Example 1.

Example 1. Minimalist illustration of closures
function foo(  ) {
var x = 10;
return function bar(  ) {
console.log(x);
}
}

var x = 5;
var barReference = foo(  );
barReference(  ); //What gets printed? 10 or 5

Depending on your programming background, the previous code snippet might actually surprise you. As it turns out, the value 10 is printed to the screen because, in JavaScript, the entire scope chain is taken into account when evaluating a function. In this case, the scope chain that is returned is associated with bar, which is returned from evaluating foo. Thus, when barReference is evaluated, the value for x is looked up on the fly, and is tracked down in the body of foo. This is directly contrary to many programming languages, which would look up the context in the most immediate scope.

In JavaScript, functions are "first-class" objects that you can pass around, assign to variables, etc., and many of Dojo's design patterns leverage this characteristic heavily.

Although JavaScript closures are normally considered an advanced topic, the sooner you have a firm grasp on closures, the sooner you'll be on your way toward mastering the language and the better you'll understand many pieces of Dojo's design philosophy. In practical terms, that means you'll be more productive, able to track down tricky bugs a lot faster, and perhaps even become a more interesting person. (Well, two out of three isn't bad.) Consult David Flanagan's legendary JavaScript: The Definitive Guide (O'Reilly) for an excellent analysis of closures.

#### Context

JavaScript's extreme dynamism equips it with tremendous flexibility, and one of the most interesting yet least understood facets of its dynamism involves context. You probably already know that the default this context for browser-based JavaScript is the global window object. For example, the following statements should evaluate to true for virtually every browser implementation:

//the default context for a document is the window
console.log(window ==this); //true

//document is a shortcut for window.document
console.log(document == window.document); //true

With respect to Function objects, the keyword this is specifically used to refer to its immediate context. For example, you may have seen this used in a JavaScript Function object somewhat like the following:

function Dog(sound) {
this.sound = sound;
}

Dog.prototype.talk = function(name) {
console.log(this.sound + "," + this.sound + ". My name is", name);
}

dog = new Dog("woof");
dog.talk("fido"); //woof, woof. my name is fido

If you come from Java or a similar object-oriented background, the way that sound is looked up relative to the current object probably seems familiar enough. Nothing interesting is happening yet. However, matters can get more complicated if you bring in the built-in call function. Take a moment to study the following contrived example that introduces the call function at work:

function Dog(sound) {
this.sound = sound;
}

Dog.prototype.talk = function(name) {
console.log(this.sound + "," + this.sound + ". my name is", name);
}

dog = new Dog("woof");
dog.talk("fido"); //woof, woof. my name is fido

function Cat(sound) {
this.sound = sound;
}

Cat.prototype.talk = function(name) {
console.log(this.sound + "," + this.sound + ". my name is", name);
}

cat = new Cat("meow");
cat.talk("felix"); //meow, meow. my name is felix

cat.talk.call(dog, "felix") //woof, woof. my name is felix

Whoa! That last line did something pretty incredible. Through the cat object instance, it invoked the talk method that is bound to the cat prototype and passed in the name parameter to be used as usual; however, instead of using the sound that is bound to cat's this, it instead used the sound value that is bound to dog's this because dog was substituted in for the context.

It's well worth a few moments to tinker around with the call function to get more comfortable with it if it's new to you. In many less dynamic programming languages, the ability to redefine this would almost be ludicrous. As a potent language feature, however, JavaScript allows it, and toolkits like Dojo leverage this kind of inherent dynamism to do some amazing things. In fact, some of these amazing things are coming up in the next section.

Although the intent of this book isn't to provide exhaustive JavaScript language coverage that you could read about in JavaScript: The Definitive Guide, you may find it instructive to know that apply is a function that works just like call except that instead of accepting an unspecified number of parameters to be passed into the target function, it accepts only two parameters, the latter parameter being an Array, which can contain an unsaid number of values that become the built-in arguments value for the target function. Essentially, you'll choose the one most convenient for you.

#### Anonymous functions

In JavaScript, Function objects may be passed around just like any other type. Although using anonymous functions inline can definitely provide some syntactic sugar that reduces the clutter and makes code more maintainable, a perhaps more significant feature of anonymous functions is that they provide a closure that protects the immediate context.

For example, what does the following block of code do?

//Variable i is undefined.

for (var i=0; i < 10; i++) {
//do some stuff with i
}
console.log(i); // ???

If you thought that the console statement prints out undefined, then you are sorely mistaken. A subtle but important characteristic of JavaScript is that it does not support the concept of blocked scope outside of functions, and for this reason, the values of i and any other "temporary" variables defined during iteration, conditional logic, etc., live on long after the block executes.

If it's ever prudent to explicitly provide blocked scope, you could wrap the block inside of a Function object and execute it inline. Consider the following revision:

(function(  ) {
for (var i=0; i < 10; i++) {
//do some stuff with i
}
})(  )
console.log(i); // undefined

Although the syntax is somewhat clumsy, keeping it clear of artifacts can sometimes prevent nasty bugs from sneaking up on you. Many Base language functions introduced in the following chapters provide closure (in addition to syntactic sugar and utility) to the code block being executed.

## Conventions Used in This Book

The following typographical conventions are used in this book:

Plain text

Italic

Indicates new terms, URLs, email addresses, filenames, file extensions, pathnames, directories, and Unix utilities.

Constant width

Indicates commands, options, switches, variables, attributes, keys, functions, types, classes, namespaces, methods, modules, properties, parameters, values, objects, events, event handlers, XML tags, HTML tags, macros, the contents of files, or the output from commands.

Constant width bold

Shows commands or other text that should be typed literally by the user.

Constant width italic

Shows text that should be replaced with user-supplied values.

This icon signifies a tip, suggestion, or general note.

This icon indicates a warning or caution.

### Style Conventions

Two additional conventions should also be noted as they relate to effectively communicating the meaning of content:

Qualifying references

Fully qualified namespaces are generally not used when the context is obvious. For example, if a code listing just introduced a dijit.form.Button widget, then the following discussion might opt to simply refer to the widget as Button.

Some terms such as constructor may be used in multiple ways within the same paragraph or context. Whenever this happens, the constant width font is used to differentiate whenever possible. For example, the sentence, "You create a widget by invoking an ordinary JavaScript constructor function, but a widget also has a special lifecycle method called constructor that can be used to perform initialization tasks" attempts to de-conflict the meaning of the term "constructor" by applying the constant width font.

API listings

In general, this book strives to provide standalone API listings by using a convention that relates the types of parameters by standardized constructor function names. For example, consider a function that would be invoked along the lines of loadUpArray("foo", 4) and return back ["foo", "foo", "foo", "foo"]. The API listing would be related as follows:

loadUpArray(/*String*/ value, /*Integer*/ length) //returns Array

Because JavaScript is a very dynamic, weakly typed language, however, there are some situations in which a parameter or value returned from a function could be any possible value. In these cases, the convention Any will be used to relate this feature. Whenever a parameter is optional, a question mark follows its type, like so: /*Integer?*/.

If you end up browsing Dojo source code, you may notice that some of the parameter names in the source code differ from the names the API listings use in this book. Because JavaScript function parameters are unnamed and positional, their actual names so far as an API listing is inconsequential; this language characteristic was leveraged to relate API listings in the most intuitive manner. As much care as possible was taken to provide API listings in the most uniform way possible, but there are bound to be small deviations occasionally.

## Using Code Examples

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product's documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: "Dojo: The Definitive Guide, by Matthew A. Russell. Copyright 2008 Matthew A. Russell, 978-0-596-51648-2."

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

## Safari® Books Online

When you see a Safari® Books Online icon on the cover of your favorite technology book, that means the book is available online through the O'Reilly Network Safari Bookshelf.

Safari offers a solution that's better than e-books. It's a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at http://safari.oreilly.com.

## We'd Like to Hear from You

 O'Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at:

 http://www.oreilly.com/catalog/9780596516482

 

For more information about our books, conferences, Resource Centers, and the O'Reilly Network, see our web site at:

 http://www.oreilly.com

## Acknowledgments

Writing this book has been much more than a brief stint of moonlighting and baptism by fire. Rather, it has been a journey that started long before I'd ever even heard of Dojo, JavaScript, or computers. This book is the logical fruition of life-changing events—all involving incredible people. What follows is an ultra-condensed, semi-chronological storyboard of the key happenings that all played a part in the pages that you're about to read.

This book is the culmination of seemingly disparate events in my life, but the common thread amongst all of these events is the incredible people involved in each step along the way. It is with much delight that I give so many thanks to:

• The LORD, for He is good and His steadfast love endures forever!

• Lucille Tabor, who provided a young child a mother and a home.

• Jerry Russell, who purchased a poor boy his first computer.

• David Kade, who taught a hopeful student how to think in another language.

• Deborah Pennington, who almost single-handedly turned a young punk's life around.

• Kellan Sarles, who taught an aspiring writer how to converse on paper.

• Gary Lamont, who engaged an emerging mind to think like a computer scientist.

• Derrick Story, who gave a want-to-be writer an opportunity.

• Abe Music, who first introduced me to Dojo.

• Simon St.Laurent, Tatiana Apandi, Colleen Gorman, Rachel Monaghan, and Sumita Mukherji, who provided the editorial guidance and insight that smoothed out so many of this book's rough edges.

• So many new friends from #dojo, who so generously reviewed this book's manuscript and provided feedback that made all of the difference in quality; in no particular order: Adam Peller, Sam Foster, Karl Tiedt, Bill Keese, Dustin Machi, Pete Higgins, James Burke, Peter Kristoffersson, Alex Russell, and Dylan Schiemann.

• Baseeret, who is the love of my life.

• The LORD, for He is good and His steadfast love endures forever!

—Matthew A. Russell

June 2008

[2] See http://www.cometd.com or http://www.cometdaily.com or a great coverage on Comet.

[3] See http://getahead.org/dwr for more on Direct Web Remoting.

[4] See http://www.openrecord.org for more on OpenRecord.

[5] As we'll be discussing more in subsequent chapters, "across the wire" refers to the size of content after it has been gzipped, because that's normally the way web servers transfer web pages to clients.

[6] From a conservative estimate, over 95% of the API for Base, Core, Dijit, and Util is covered in this book.