AccordionContainer
Like a TabContainer, AccordionContainer inherits from StackContainer and is a means of displaying one child at a time from a collection of widgets. The visual difference is that the container looks like a vertical accordion, and animates when each child is selected. One important difference in how you use AccordionContainer, however, is that you must use a special child container called AccordionPane that provides an explicit wrapper for its child widgets. The actual reasoning for why this is...
Dijit API DriveBy
The functions listed in Table 11-4 are too commonly used not to especially call out. They're available as part of Dijit Base and get pulled in whenever you require Dijit resources into the page. You can also fetch them by issuing a dojo.require dijit. dijit statement, as they are included in the standard build profile, which you'll read more about in Chapter 16. - For comprehensive API documentation, visit Dojo's online documen tation at http api.dojotoolkit.org. Table 11-4. Commonly used Dijit...
Themes
A Dijit theme is a fully consistent collection of CSS rules that span across the entire set of widgets. To say that another way, you might think of Dijit as being skinnable, where a theme is a kind skin that you apply. If you need to pull some widgets off the shelf and put together something quickly, themes are especially good because CSS becomes one less thing that you have to worry about implementing. As of version 1.1, Dojo includes three great-looking, prepackaged themes Predominantly light...
MappedTextBox and RangeBoundTextBox
Two well-defined form dijit classes that are not covered in this chapter include MappedTextBox and RangeBoundTextBox. Basically, MappedTextBox provides some methods for serializing its data into a String value via a custom toString method, and RangeBoundTextBox facilitates ensuring that a value is within a specified range by allowing you to pass in max and min values to the constraints object. Although it might intuitively seem like the validation in ValidationTextBox should be handling tasks...
Summary Ctq
After reading this chapter, you should be able to Use Dojo's XHR machinery to perform RESTful operations with a web server Understand how Deferreds provide the illusion of threads, even though JavaScript does not support threads Be aware that the toolkit's entire IO subsystem uses and generally returns Deferreds from function calls Be able to use Base's functions for converting forms to and from Objects and JSON Be able to use Core's IFRAME transport layer for common operations such as...
Rhino Test Harness with Dojo
Although it is possible to use DOH without Dojo, chances are that you will want to use Dojo with Rhino. Core contains some great examples that you can run by executing runner.js without any additional arguments. The default values will point to the tests located in dojo tests and use the version of Base located at dojo dojo.js. If you peek inside any of Core's test files, you'll see the usage is straightforward enough. Each file begins with a dojo.provide that specifies the name of the test...
Custom canceller
The various XHR functions all have a special cancellation function that is invoked by calling cancel , but for custom Deferreds, you can create your own custom canceller, like so console.log custom canceller If you don't return a custom Error, a default Deferred Cancelled Error is returned var d new dojo.Deferred canceller pass in the canceller to the constructor interesting stuff happens d.cancel errbacks could be ready to respond to the Deferred Cancelled Error in a special way
NumberTextBox
NumberTextBox inherits all of the great features you've grown to love from RangeBoundTextBox and its ancestors and expands upon them with customization for numeric types via the dojo.number facilities. In a nutshell, numeric value formatting defaults to the current locale and allows you to provide the constraints listed in Table 13-7. Table 13-7. NumberTextBox constraints Name Comment min and max constraints Used to check the bounds of the input, just like any other RangeBoundTextBox...
Toolbar
The Toolbar is another familiar control that abbreviates the common task of providing a collection of common commands to the user. In short, the Toolbar does nothing more than house a collection of Button dijits, which when styled appropriately, can be very aesthetically pleasing. The various prepackaged themes that come with Dijit contain classes for many of the common operations such as cut paste, bold italic, etc., which you can provide through Button's iconClass attribute. The following...
HelloWord Dijit Take Passing in Parameters
As yet another improvement to our HelloWorld dijit, let's learn how to pass in custom parameters to dijits through the template. Given the previous example, let's suppose that we want to supply the custom greeting that is to appear in our widget from its markup that appears alongside the dojoType tag. Easy just pass it in like so lt div dojoType dtdg.HelloWorld greeting Hello World gt lt div gt Passing in the parameter for a widget that is programmatically created is just as simple var hw new...
The Widget Lifecycle
To come full circle to the discussion about the creation pattern dojo.declare provides from back in Chapter 10, here's how the _Widget lifecycle plugs in preamble Object params, DOMNode node precursor to constructor can manipulate superclass constructor args constructor Object params, DOMNode node fire any superclass constructors fire off any mixin constrctors fire off the local class constructor, if provided postscript Object params, DOMNode node _Widget implements postscript to kick off the...
ParentChild Relationships with Container and Contained
After you've been rolling with _Widget and _Templated for a while, it won't be long before you find that it's convenient to have a widget that contains some children widgets. The has-a relationship pattern is quite common in programming and it is no different with Dojo. The _Container and _Contained mixins are designed to facilitate the referencing back and forth between parents and children that often needs to happen. Table 12-1 summarizes the API. Table 12-1. _Container and _Contained mixins...
HorizontalSlider
Suppose that as a caffeine junkie, you want to create a horizontal slider that denotes caffeine levels for various beverages. Your first stab at getting a plain vanilla slider into the page might be something like the Example 13-13, remembering to first require dijit.form.Slider into the page. Example 13-13. HorizontalSlider Take 1 lt div name caffeine value 100 maximum 175 minimum 2 style margin 5px width 300px height 20px gt lt script type dojo method event onChange args newValue gt...
Cookies
Because HTTP is a stateless protocol, as soon as a web server finishes serving up a page, it knows nothing else about you. While this aspect of the Web is magnificent in many respects, it is less than ideal for situations in which an application could personalize a page based upon preferences you've already defined. For example, it might be nice for a weather-related site to remember your zip code so that you don't have to enter it every single time you visit the page. Cookies are a concept...
XHR Examples
At an absolute minimum, the arguments for an XHR request should include the URL to retrieve along with the load function however, it's usually a very good idea to include an error handler, so don't omit it unless there you're really sure you can't possibly need it. Here's an example dojo.addOnLoad function dojo.xhrGet url someText.html, the relative URL Run this function if the request is successful load function response, ioArgs console.log successful xhrGet, response, ioArgs Set some...
Event Propagation
There may be times when you need to suppress the browser's built-in handling of some DOM events and instead provide custom handlers for these tasks yourself via dojo.connect. Two fairly common cases that occur are when you'd like to suppress the browser from automatically navigating when a hyperlink is clicked and when you'd like to prevent the browser from automatically submitting a form when the Enter key is pressed or the Submit button is clicked. Fortunately, stopping the browser from...
Serializing and Deserializing Custom Data Types
Although not mentioned until now, you should be aware of one additional feature provided by ItemFileReadStore and ItemFileWriteStore the ability to pack and unpack custom data types. The motivation for using a type map is that it may often be the case that you need to deal with attributes that aren't primitives, object literals, or arrays. In these circumstances, you're left with manually building up the attributes yourself introducing cruft in your core logic or streamlining the situation by...
The Box Model
The CSS box model is a fairly simple topic, but because there are so many inconsistent implementations of it that are available on the Web, things get messy pretty quickly. This short section does little more than scratch the surface, because you really do want to turn to an authoritative reference such as Eric Meyer's CSS The Definitive Guide O'Reilly to really get to the bottom of it all. If various inconsistent implementations of the box model aren't enough, there's also the issue of keeping...
Form submissions with IFRAMEs
Another common use case for IFRAMEs is submitting a form behind the scenes maybe even a form that involves a file upload, which would normally switch out the page. Here's a CherryPy script that handles a file upload set this to wherever you want to place the uploaded file outfile open local_file_path, 'wb' data inbound.file.read 8l92 if not data break return a simple HTML file as the response return start up the web server and have it listen on 8080 cherrypy.quickstart Content , ' ' And here's...
CurrencyTextBox
The CurrencyTextBox is the farthest dijit from the common ancestor, inheriting from NumberTextBox, and utilizes dojo.currency for much of its formatting handiwork. This dijit, however, provides only one additional attribute, currency, which is formatted according to its specific locale. Values for currency must be one of the three letter sequences specified in the ISO4217 currency code standard, available from Anytime international characters such as currency symbols are used, you'll want to be...
Iterating Over Elements
The forEach function passes each element of an array into a function that takes a single parameter and does not return any value at all. It is generally used to iterate over each element of an array as an ordinary for loop. Here's the signature dojo.forEach Array array, Function function No return value In its simplest form forEach works like so Some obvious benefits of forEach is that it introduces less clutter than explicitly introducing a for loop and requiring you to manage a counter...
JSON RPC Example
parameters name list name sumOfSquares, parameters name list instantiate the service var rpcObject new dojo.rpc.JsonService o call the service and use the Deferred that is returned to add a var sum rpcObject.sum 4,8,15,16,23,42 sum.addCallback function response console.log the answer is , response add more callbacks, errbacks, etc. call sumOfSquares the very same way lt script gt lt body gt lt body gt lt html gt Hopefully, you see the connection that if there were lots of methods communicating...
StackContainer
A StackContainer is a layout dijit that displays a sequence of tiles one at a time. A StackContainer is conceptually just like a slideshow in which you can page backward and forward through a stack of tiles. Like LayoutContainer, you provide any number of child widgets to the StackContainer, and it takes care of the display. In its most basic usage, you simply page through the available tiles, as shown in Example 14-4. Example 14-4. Creating a StackContainer in markup lt div id stack style...
TitlePane
A TitlePane is a widget that always displays a title, but whose body may be expanded or collapsed as needed the actual resize is done with an animated wipe-in or wipe-out. As a descendant of ContentPane, TitlePane also has access to all of the inherited methods for loading content remotely, although they are not explicitly covered again in this section. Refer to the previous chapter for complete coverage of ContentPane. Example 15-5 shows the elementary usage. Example 15-5. Typical TitlePane...
ProgressBar
The ProgressBar dijit behaves just like any other progress bar you've seen in an application, and it comes in both determinate and indeterminate variations. One of the greatest things about it is that there's just not that much to say. In fact, Example 15-3 should do a good job of speaking for itself. Example 15-3. Typical indeterminate ProgressBar usage lt div dojoType dijit.ProgressBar indeterminate true Of course, there will certainly be times when you'll want to fetch a real update from the...
File downloads with IFRAMEs
Because triggering a file download via an IFRAME is a common operation, let's try it out. Here's a CherryPy file that serves up a local file when you navigate to http localhost 8080 . We'll use this URL in our dojo.io.frame.send call to the server from cherrypy.lib.static import serve_file import os update this path to an absolute path on your machine serve up a file cherrypy.expose def download self return serve_file local_file_path, application x-download, attachment start up the web server...
Deferred Examples Via CherryPy
Let's get warmed up with a simple routine on the server that briefly pauses and then serves some content. The pause is just a way of emphasizing the notion of asynchronous behavior. The complete CherryPy file that provides this functionality follows import cherrypy from time import sleep import os a foo.html file will contain our Dojo code performing the XHR request and that's all the following config directive is doing 'tools.staticfile.filename' os.path.join current_dir, 'foo.html' this is...
Dojo Objective Harness DOH
Automated testing practices for web applications are becoming increasingly common because of the sheer amount of coding and complexity involved in many of today's rich Internet applications. DOH uses Dojo internally but is not a Dojo-specific tool like ShrinkSafe, you could use it to create unit tests for any JavaScript scripts, although no DOM manipulation or browser-specific functions will be available. DOH provides three simple assertion constructs that go a long way toward automating your...
Asynchronous Browser Test Example
Almost any web application test suite worth its salt is going to involve a significant number of tests that depend upon asynchronous conditions such as waiting for an animation to happen, a server side callback to occur, and so on. Example 16-4 introduces how you can create asynchronous test with DOH. The key concept is that a doh.Deferred pretty much an ordinary dojo.Deferred with some tweaks except that it is internal to DOH and, as such, doesn't have external dependencies. Chapter 4 included...
Custom Avatars
The small icon that temporarily appears when an item from a Source is being moved around is called an avatar. Although the standard avatar is quite nice, you may want to construct your own at some point. The following code adjustment illustrates how to define custom text for an avatar by overriding the creator method because this method is used to create an avatar representation of one or more nodes. In this particular circumstance, we'll choose to override creator in markup. The layout is also...
Lifecycle methods
The most notable effect of mixing in _Templated is that it results in overriding _Widget's buildRendering method. Here's a synopsis of buildRendering While _Widget provides this method, _Templated overrides it to handle the messy details associated with fetching and instantiating a dijit's template file for on screen display. Generally speaking, you probably won't implement your own buildRendering method. If you ever do override this method, however, ensure that you fully understand...
Data API Overview
The most basic atom of the dojo.data API is called an item, which is composed of key value pairs called attributes and attribute values in dojo.data parlance conceptually, you can think of an item as a plain old JavaScript Object. However, although the underlying implementation may very well be a JavaScript Object, be careful to use the provided APIs for accessing it, as the internal representation may be something entirely different. For example, some data abstractions may use a DOM model for...
Animation DragandDrop Fun
Drag-and-drop combined with animations are an incredibly powerful combination. Take a moment to review and experiment with the following block of code, which combines very basic concepts from drag-and-drop in the previous chapter with what you've been learning about in this one it's illustrated in Figure 8-6. Figure 8-6. A visualization of the xA5 easing function Figure 8-6. A visualization of the xA5 easing function lt title gt Animation Drag and Drop Fun lt title gt lt script gt lt script...
MultiSelect
MultiSelect is a simple wrapper with the attributes listed in Table 13-11 around a native SELECT element with the attribute multi true that inherits from _FormWidget. The primary reason that it is included in Dijit is because it facilitates interaction with the dijit.Form wrapper coming up later in this chapter and streamlines the task of otherwise having to style the SELECT element yourself. Table 13-11. MultiSelect Name Comment size The number of elements to display on a page. 7 by default....
ContentPane
A ContentPane is the most basic layout tile and it inherits directly from _Widget conceptually, it is like a super-duper variation of an iframe except that it fits right into the page with all sorts of bells and whistles, not the least of which are the ability to render arbitrary snippets of HTML not just full documents , reload content via XHR on demand, render widgets, and respect the page's theme. More often than not, a ContentPane is contained within another widget such as a TabContainer,...
Dialog
The Dialog dijit is conceptually like a pop up that sets up a translucent underlay below it. While it is visible, you cannot respond to anything below it, making it ideal for situations in which you need to temporarily prevent access to controls on a page or force the user to acknowledge or respond to an alert. But in addition to the obvious uses, you might also use a Dialog for almost any situation in which the alternative would be to pop up a new window. From an implementation standpoint,...
Cloning Objects
Although JavaScript performs shallow copies in assignments involving JavaScript objects and DOM nodes, you may often find yourself needing to clone, or perform deep copies, of object hierarchies. Base's clone function is a highly efficient ticket to achieving just that. Consider the following simple example console.log fool.bar console.log foo2.bar fool.bar qux changing fool also changes foo2 console.log fool.bar qux console.log foo2.bar qux foo4 dojo.clone foo3 deep copy console.log foo3.bar...
HelloWorld Dijit Take Modifying The Template
Suppose you want your dijit to be a little less generic. Instead of displaying the same static message every time the page is loaded, a good first step might be to make the custom message that is displayed dynamic. One of the wonderful mechanisms that Dojo employs for keeping the logical concept of a dijit cohesive is that you can reference dijit properties that are defined in your JavaScript source file inside the template. Although referencing dijit properties from inside the template is only...
FilteringSelect
A FilteringSelect is an enhanced version of the ordinary HTML select element in that provides a drop-down list of mandatory values and submits the hidden values and the displayed values. While FilteringSelect looks like and shares a lot of features with ComboBox, including the ability to filter a drop-down list as text is typed and the ability to fetch data from a serve via a store, it is built upon an HTML SELECT element. Three particularly important distinctions between a FilteringSelect and...
Multiple Inheritance Oddities
In the earlier example involving shapes, there was no particular need to be concerned with the argument list from a Circle getting passed up to a Shape because a Circle built directly upon a Shape. Furthermore, it made good sense and was even convenient to include Shape's constructor argument as the first argument of Circle's constructor. In this past example with lions, tigers, and ligers, the constructors are all single argument functions that do the same thing, so there's no real issue...
Injecting Deferreds into XHR functions
Another great feature of a Deferred is that you have a clean way of canceling an asynchronous action before it completes. The following refinement to our previous example illustrates both the ability to cancel an in-flight request as well as injecting a Deferred into the load and error handlers of the request lt title gt Fun with Deferreds lt title gt lt script type text javascript lt script gt lt script type text javascript gt dojo.addOnLoad function d.addCallback function result console.log...
Manually creating a hidden IFRAME
As a final consideration, there may be times when you need to create a hidden IFRAME in the page to load in some content and want to be notified when the content finishes loading. Unlike the dojo.io.iframe.send function, which creates an IFRAME and immediately sends some content, the dojo.io.iframe.create function creates an IFRAME and allows you to pass a piece of JavaScript that will be executed when the IFRAME constructs itself. Here's the API String onLoadString, String url Returns DOMNode...
Commonalities between DateTextBox and TimeTextBox
Two additional methods that are available for TimeTextBox and DateTextBox are getDisplayedValue and setDisplayedValue. The difference between these methods and the ordinary getValue and setValue approaches involves the difference in what is actually displayed in the dijit versus what data type is used internally by the dijit. Both TimeTextBox and DateTextBox use JavaScript Date objects internally, and getting this Date object is just one method call away. Recall that the machinery inherited...
Dijit Overview
Dijit is the fantastic layer of widgets that the toolkit provides as drop-in replacements for the standard HTML web controls. This chapter paves the way for Part II by starting out with a fairly nontechnical discussion of Dijit's motivation, philosophy, and goals as an off-the-shelf resource, which dovetails into a discussion of how designers and ordinary page creators can use dijits in markup with little to no programming. The chapter concludes with a guided tour that provides a thorough...
Mixin Pattern
For the sake of demonstrating an alternate paradigm to the typical inheritance groupthink, consider Example 10-3's approach of using mixins to model shapes and circles in a different way. It's especially noteworthy to make the connection that mix-ins heavily leverage duck typing and has-a relationships. Recall that the concept of ducktyping is based upon the idea that if something quacks like a duck and acts like a duck, then it may as well be a duck. In our circumstance, the concept translates...
Drag Events
It's likely that you'll want to detect when the beginning and end of drag action occurs for triggering special effects such as providing a visual cue as to the drag action. Detecting these events is a snap with dojo.subscribe and dojo.connect. Example 7-3 shows another rendition of Example 7-2. Example 7-3. Connecting and subscribing to drag Events lt title gt Yet More Fun with Moveable lt title gt lt style type text css gt background FFFFBF border-bottom 1px solid black border-left 1px solid...
Hitching Up Callbacks
Chapter 2 introduced hitch, a function that can be used to guarantee that functions are executed in context. One common place to use hitch is in conjunction with XHR callback functions because the context of the callback function is different from the context of the block that executed the callback function. The following block of code demonstrates the need for hitch by illustrating a common pattern, which aliases this to work around the issue of context in the callback Suppose you have the...
IFRAME Transports
Core provides an IFRAME transport that is handy for accomplishing tasks behind the scenes that would normally require the page to refresh. While XHR methods allow you to fetch data behind the scenes, they don't lend themselves to some tasks very well form submissions, uploading files, and initiating file downloads are two common examples of when IFRAME transports come in handy. Following the same pattern that the rest of the IO system has established, using an IFRAME transport requires passing...
onblur
As an example, consider the use case of capturing mouse movement events over a particular element. You'd simply fill in the function for the onmouseover function like so function evt console.log evt you should really do something more interesting The event objects that are available via the DOM Event methods are standardized, because internally dojo.connect is being used. The event model as provided via dojo. connect is standardized in accordance with the W3C specification. There is no direct...
Motivation for Managing the Mayhem
For anything but the smallest of projects, the benefits of using this approach are irrefutable. The ease of maintenance and simplicity gained in extending or embedding code in multiple places is a key enabler to getting work done quickly and effectively. As obvious as it may sound, importing code in the manner just described hasn't always been obvious to web developers, and many web projects have turned into difficult-to-maintain monstrosities because of improper source code management in the...

