10 Reasons Why Your Projects Should Use the Dojo Toolkit

10 Reasons Why Your Projects Should Use the Dojo Toolkit

Tutorial Details

The most powerful and underutilized JavaScript utility is one and the same: the Dojo Toolkit. While nearly every JavaScript framework or toolkit promises to do everything you need, the Dojo Toolkit makes the most compelling case for that statement being true. This post will cover many of the most powerful features of the Dojo Toolkit, and in doing so will make the case for why you should use the Dojo Toolkit for your next project.


1. Modularity and AMD Loading

Don’t start you next project without checking out all of the features Dojo has to offer!

As our client side JavaScript code grows in size, and it will, modularity will be key to keeping our applications fast, maintainable, and performant. The days of using one lump library file without asynchronous loading are over. For years, the Dojo Toolkit’s code has been the shining example of modularity, using dojo.require (before builds) to dynamically pull in only the resources required by the page. The default method of loading JavaScript resources was synchronously, though there was a cross-domain option which was asynchronous.

Dojo has since moved to an asynchronous loader, written by Rawld Gill, which masterfully loads all resources asynchronously, vastly improving speed. To load a few JavaScript resources, you can code something like the following:

// The require function directs the loader to attempt to load resources in the first array
// If the resources have already been loaded, their cached objects will be used
require(

	// An array of modules to load
	["dojo/on", "dojo/touch", "dijit/form/Button", "dojo/domReady!"], 

	// A callback function with loaded module objects as arguments
	// Must be added in the same order as they were loaded
	function(on, touch, Button) {

		// Now do something with the components we've loaded!

});

To declare a module, simply code the following pattern:

// Using 'define' instead of 'require' because we're defining a module
define(

	// Again, an array of module dependencies for the module we'd like to build
	["dojo/aspect", "dojo/_base/declare", "dijit/layout/BorderContainer"]

	// Again, a callback function which should return an object
	function(aspect, declare, BorderContainer) {

		// Return a module (object, function, or Dojo declared class)
		return declare("mynamespace.layout.CustomBorderContainer", [BorderContainer], {

			// Custom attributes and methods here

		});

})

This simple define method, used by nearly all AMD loaders, is incredibly simple and structured. very much like a require block, so it’s very easy to use. The items listed in the dependency array are loaded before the callback is run. The callback (usually) returns a function or object representing the module. An easy pattern that loads fast, maintains modularity, and allows developers to load only what they need!

Dojo’s feature-rich loader also provides plugins, such as domReady, for listening for DOM readiness, and has feature detection with hasJS. The loader is also intelligent enough to conditionally load modules based on environment or configuration:

// This code is featured in the dojo/Deferred module
define([
	"./has",
	"./_base/lang",
	"./errors/CancelError",
	"./promise/Promise",
	"./has!config-deferredInstrumentation?./promise/instrumentation"
], function(has, lang, CancelError, Promise, instrumentation){

	// ...

});

Not only is Dojo modular as can be, it provides a baked-in loader for you!

Dojo Module and AMD Resources


2. Classes and Extensibility with dojo/declare

While JavaScript doesn’t provide a true class system, the Dojo Toolkit provides a class-like inheritance pattern using dojo/declare. Declare is used throughout the framework so that developers can:

  • cut down on or even eliminate repeated code
  • use “mixins” to share functionality amongst many other classes
  • easily extend existing classes for increased customization
  • share modules of code between different projects
  • safely create “fixed” classes when there’s a bug in an existing Dojo class

Dojo’s class system uses prototypal inheritance, allowing prototypes to be inherited and thus children classes can be as powerful as parents due to the shared prototype. Using dojo/declare is incredibly easy:

// Of course we need to use define to create the module
define([
	// Load dojo/declare dependency
	"dojo/declare",

	// Also load dependencies of the class we intend to create
	"dijit/form/Button",
	"dojo/on",
	"mynamespace/_MyButtonMixin" // Mixins start with "_"
], function(declare, Button, on, _MyButtonMixin) {
	
	// Return a declare() product, i.e. a class
	return declare(

		// First argument is the widget name, if you're creating one
		// Must be in object syntax format
		"mynamespace.CustomButton",

		// The second argument is a single object whose prototype will be used as a base for the new class
		// An array can also be used, for multiple inheritance
		[ Button, _MyButtonMixin ],

		// Lastly, an object which contains new properties and methods, or
		// different values for inherited properties and methods
		{
			myCustomProperty: true,

			value: "Hello!",

			myCustomMethod: function() {
				// Do stuff here!
			},

			methodThatOverridesParent: function(val) {
				this.myCustomMethod(val);

				// Calling "this.inherited(arguments)" runs the parent's method
				// of the same, passing the same params
				return this.inherited(arguments);
			}
		}
	);
});

While the class above doesn’t set out to accomplish a real task (it’s simply an example), it illustrates code reuse, via the inheritance chain and mixins; it also shows how a child class can call a parent class’ same method to cut down on repeated code.

Another advantage to using Dojo’s class system is that all properties and methods are customizable — there is no “options” object that limits the amount of properties customizable on Dojo classes. Everything is easily changed and extended throughout the class creation process.


3. Aspects and “Function to Function Events”

Aspects are one of the most powerful and essential pieces of advanced web application development…and the Dojo Toolkit has provided them for years. Instead of triggering functionality after a traditional user event, like click, mouseover, or keyup, aspects allow you to trigger function B before or after function A is executed. Essentially, you can connect functions to functions — brilliant!

Triggering a function after another function looks like:

// after(target, methodName, advisingFunction, receiveArguments);
aspect.after(myObject, "someMethod", function(arg1, arg2) {
	
	// Execute functionality after the myObject.doSomething function fires

}, true);
	

Ensuring that function B fires before function A is just as easy!

aspect.before(myObject, "someMethod", function(arg1, arg2) {
	
	// This function fires *before* the original myObject.someMethod does

});

Aspects are extremely helpful when creating advanced UI’s with Dijit. Listening for events on one widget or class can trigger a change in other widgets, allowing developers to create one large, controlling widget out of many small:

var self = this;
aspect.after(this.submitButton, "onClick", function() {

	// The submit button was clicked, trigger more functionality
	self.showAjaxSpinner();

});

The aspect resource was previously found with dojo.connect.

Aspect Resources


4. Deferreds and Unified AJAX Transports

I cannot endorse this UI framework enough. When I say it’s unparalleled, I cannot emphasize how much I mean it. There is nothing close.

Deferreds are object-based representations of asynchronous operations, allowing for async operation states to easily be passed from one place to another. One of jQuery’s most recent and important additions was Deferreds. Coincidentally, the mantra of the Dojo team is “Dojo did it.” The Dojo Toolkit has featured Deferreds for several years, using them for simple and advanced AJAX operations, animations, and more.

Along with being on the forefront of Deferred objects, Dojo also pioneered several IO handling methods outside of standard XMLHTTPRequest, including a window.name wrapper, dojo/io/iframe for AJAX file uploading, and more. So when are Deferred objects used within Dojo? Whenever an asynchronous / AJAX action takes place! Deferreds are returned from XHR requests, dojo/io requests, animations, and more!

// Fire an AJAX request, getting the Deferred in return
var def = xhr.get({
	url: "/getSomePage"
});

// Do lots o' callbacks
def.then(function(result) {
	result.prop = 'Something more';

	return result;
}).then(function(resultObjWithProp) {

	// ....

}).then(function() {

	// ....

});

And then what does dojo/io/iframe‘s API look like?

require(["dojo/io/iframe"], function(ioIframe){
	// Send the request
	ioIframe.send({
		form: "myform",
		url: "handler.php",
		handleAs: "json"

	// Handle the success result
	}).then(function(data){

		// Do something

	// Handle the error case
	}, function(err){

		// Handle Error

	}). then(function() {

		// More callbacks!

	})
});

The beauty in Dojo using Deferreds for each AJAX operation is that, no matter the method, you always know you’ll receive a Deferred in return, speeding up development and unifying the API. Dojo 1.8 will see the introduction of dojo/request, a new consolidation of AJAX methods. Here are a few examples of how the dojo/request API will be used in the future:

// The most basic of AJAX requests
require(["dojo/request"], function(request){
	request("request.html").then(function(response){
		// do something with results
	}, function(err){
		// handle an error condition
	}, function(evt){
		// handle a progress event
	});
});

A unified API makes development faster and code more compact; the new dojo/request module by Bryan Forbes promises to make Dojo even more developer friendly!

Deferred and AJAX Resources


5. Dijit UI Framework

Dijit ThemeTester

Without a doubt, the Dojo Toolkit’s biggest advantage over other JavaScript frameworks is its Dijit UI framework. This unparalleled set of layout, form, and other tools boasts:

  • complete, “out of the box” localization
  • full accessibility support
  • advanced layout widgets to ease the pains of 100% height elements, effort in creating custom splitters and layout modification, etc.
  • form widgets with increased usability and built in validation
  • many themes, the newest of which is called “claro”
  • LESS files for custom themeing
  • very modular code, allowing for ultimate customization and extension of existing widgets

Dijit also allows for declarative and programmatic widget creation; declarative widget creation looks like:

<div data-dojo-type="dijit.form.Button" data-dojo-props="label:'Click Me!'"></div>

…whereby traditional JavaScript widget creation looks like:

require(["dijit/form/Button"], function(Button) {
	// Create the button programmatically
	var button = new Button({
		label: 'Click Me!'
	}, "myNodeId");
});

There are several dozen Dijit widgets provided within the dijit namespace, and a few dozen more available within the dojox namespace. The Dijit UI framework isn’t just a few helpful UI widgets, as something like jQueryUI is; Dijit is a enterprise-ready, enterprise-tested UI framework.

Dijit UI Resources

In my two years at SitePen, I worked almost exclusively with Dijit and the intricacies of creating flexible, localizable, efficient widgets. I cannot endorse this UI framework enough. When I say it’s unparalleled, I cannot emphasize how much I mean it. There is nothing close.


6. Dojo Mobile

Dojo Mobile

As with almost every problem on the web, Dojo has a solution; in this case, Dojo’s answer to mobile lives within the dojox/mobile namespace. Dojo’s excellent mobile solution provides:

  • a device detection utility
  • themes for iOS, Android, Blackberry, and “common” theme
  • mobile form widgets
  • layout widgets and panes
  • support for desktop, allowing for easier debugging

Mobile widgets can be created declaratively or programmatically, just like Dijit widgets. Mobile views can be lazily rendered and swapping between views is seamless. The HTML anatomy of a dojox/mobile page is fairly simple:

<!DOCTYPE html>
<html>
	<head>
	<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/>
	<meta name="apple-mobile-web-app-capable" content="yes" />
	<title>Your Application Name</title>

	<!-- custom stylesheets will go here -->

	<!-- dojo/javascript will go here -->

	</head>
	<body>

	<!-- application will go here -->

	</body>
</html>

By using dojox/mobile/deviceTheme, we can detect the user device and apply the proper theme:

// Will apply the device theme base on UA detection
require(["dojox/mobile/deviceTheme"]);
	

With the device theme in place, the next step is requiring the widgets used by our specific mobile application, as well as any other custom classes we desire:

// Pull in a few widgets
require([
	"dojox/mobile/ScrollableView",
	"dojox/mobile/Heading",
	"dojox/mobile/RoundRectList",
	"dojox/mobile/TabBar",
	"dojox/parser"
]);

Once the JavaScript resources have been required, it’s time to declaratively add a series of views and widgets that make up the application:

<!-- sample taken from Dojo's TweetView:  http://dojotoolkit.org/documentation/tutorials/1.7/mobile/tweetview/app/ -->

<!-- tweets view -->
<div id="tweets" data-dojo-type="dojox.mobile.ScrollableView" data-dojo-props="selected: true">
	<h1 data-dojo-type="dojox.mobile.Heading">
		<!-- the refresh button -->
		<div data-dojo-type="dojox.mobile.ToolBarButton" data-dojo-props="icon: 'images/refresh.png'" class="mblDomButton tweetviewRefresh" style="float:right;"></div>
		Tweets
	</h1>
	<ul data-dojo-type="dojox.mobile.RoundRectList">
		<li data-dojo-type="dojox.mobile.ListItem">
			Tweet item here
		</li>
	</ul>
</div>

<!-- mentions view -->
<div id="mentions" data-dojo-type="dojox.mobile.ScrollableView">
	<h1 data-dojo-type="dojox.mobile.Heading">
		<!-- the refresh button -->
		<div data-dojo-type="dojox.mobile.ToolBarButton" data-dojo-props="icon: 'images/refresh.png'" class="mblDomButton tweetviewRefresh" style="float:right;"></div>
		Mentions
	</h1>
	<ul data-dojo-type="dojox.mobile.RoundRectList">
		<li data-dojo-type="dojox.mobile.ListItem">
			Mention tweet item here
		</li>
	</ul>
</div>

<!-- settings view -->
<div id="settings" data-dojo-type="dojox.mobile.ScrollableView">
	<h1 data-dojo-type="dojox.mobile.Heading">Settings</h1>
	<h2 data-dojo-type="dojox.mobile.RoundRectCategory">Show</h2>
	<ul data-dojo-type="dojox.mobile.RoundRectList">
		<li data-dojo-type="dojox.mobile.ListItem">
			Setting item here
		</li>
	</ul>
</div>

One incredible advantage to using dojox/mobile is that the API for widget creation is the same as all other Dijit classes, so speed in development is increased for those that have used Dijit before; for those that are new to Dojo, the mobile API is still incredibly easy.

dojox/mobile Resources


7. GFX and Charting

Ajax London Logo

Without a doubt, the Dojo Toolkit’s biggest advantage over other JavaScript frameworks is its Dijit UI framework.

CSS animations are a great visualization tool, as is animated imagery, but neither are as flexible and powerful as vector graphic creation and manipulation. The most popular client side vector graphic generation tool has always been Raphael JS, but Dojo’s GFX library is unquestionably more powerful. GFX can be configured to render vector graphics in SVG, VML, Silverlight, Canvas, and WebGL. GFX provides a usable wrapper to create each vector graphic shape (ellipse, line, path, etc.) for speed in development, and allows developers to:

  • Skew, rotate, and resize graphics
  • Animate fill, stroker, and other graphic properties
  • Add linear and circular gradients to a shape
  • Listen and respond to mouse events
  • Group shapes for easier management and animation

Creating a simple set of shapes over a canvas could look like:

require(["dojox/gfx", "dojo/domReady"], function(gfx) {
	
	gfx.renderer = "canvas";
	
	// Create a GFX surface
	// Arguments:  node, width, height
	surface = gfx.createSurface("surfaceElement", 400, 400);
	
	// Create a circle with a set "blue" color
	surface.createCircle({ cx: 50, cy: 50, rx: 50, r: 25 }).setFill("blue");

	// Crate a circle with a set hex color
	surface.createCircle({ cx: 300, cy: 300, rx: 50, r: 25 }).setFill("#f00");

	// Create a circle with a linear gradient
	surface.createRect({x: 180, y: 40, width: 200, height: 100 }).
	setFill({ type:"linear", 
		x1: 0,                           
		y1: 0,   //x: 0=>0, consistent gradient horizontally
		x2: 0,   //y: 0=>420, changing gradient vertically
		y2: 420,                         
		colors: [
			{ offset: 0,   color: "#003b80" },
			{ offset: 0.5, color: "#0072e5" },
			{ offset: 1,   color: "#4ea1fc" }
		]
	});

	// Create a circle with a radial gradient
	surface.createEllipse({
		cx: 120,
		cy: 260,
		rx: 100,
		ry: 100
	}).setFill({
		type: "radial",
		cx: 150,
		cy: 200,
		colors: [
			{ offset: 0,   color: "#4ea1fc" },
			{ offset: 0.5, color: "#0072e5" },
			{ offset: 1,   color: "#003b80" }
		]
	});
	
});

Dojo GFX

An API that’s been written on top of GFX is Dojo’s powerful dojox/charting library. Visualization of data via charting is popular and for good reason; simply reading numbers doesn’t provide, well, the full picture. The dojox/charting library allows for:

  • multiple plots
  • animated chart elements
  • plugins, including MoveSlice (animates pie chart slices), Tooltip, Magnify, and Highlight
  • self-updating charts, powered by Dojo data stores

A basic pie chart can be created using the following Dojo JavaScript code:

<script>

	// x and y coordinates used for easy understanding of where they should display
	// Data represents website visits over a week period
	chartData = [
		{ x: 1, y: 19021 },
		{ x: 1, y: 12837 },
		{ x: 1, y: 12378 },
		{ x: 1, y: 21882 },
		{ x: 1, y: 17654 },
		{ x: 1, y: 15833 },
		{ x: 1, y: 16122 }
	];
		
	require([
		// Require the widget parser
		"dojo/parser",

		 // Require the basic 2d chart resource
		"dojox/charting/widget/Chart",
		
		// Require the theme of our choosing
	    "dojox/charting/themes/Claro",

		// Charting plugins: 

		// Require the Pie type of Plot 
		"dojox/charting/plot2d/Pie"

	]);

</script>
<!-- create the chart -->
<div 
	data-dojo-type="dojox.charting.widget.Chart" 
	data-dojo-props="theme:dojox.charting.themes.Claro" id="viewsChart" style="width: 550px; height: 550px;">

	<!-- Pie Chart: add the plot -->
	<div class="plot" name="default" type="Pie" radius="200" fontColor="#000" labelOffset="-20"></div>

	<!-- pieData is the data source -->
	<div class="series" name="Last Week's Visits" array="chartData"></div> 
</div>

Dojo Charting

While the code above creates a simple pie chart, Dojo’s dojox/charting library is capable of much, much more.

dojox/gfx and dojox/charting Resources


8. SitePen’s dgrid

SitePen Dojo dgrid

SitePen, a JavaScript consultancy founded by Dojo Founder Dylan Schiemann, sought out to replace DojoX’s clunky and bloated Grid widgets with a very fast, extensible, and editable grid widget; they’ve accomplished that task with dgrid. dgrid features:

  • numerous themes and is easily themeable
  • complete mobile compatability
  • sortable rows
  • onDemand grid utilities, allowing for lazy-loading of grid data
  • tree-grid capabilities
  • editable grid contents using Dijit widgets
  • extensions including column resizing, drag and drop, pagination, and more

SitePen has done an outstanding job documenting each component of dgrid, so getting started creating your own feature-rich grids will be incredibly easy!

dgrid Resources


9. DOH Testing Framework

Not only is Dojo modular as can be, it provides a baked-in loader for you!

Testing is as important, if not more important, on the client side than server side. With the range of browsers available, and the varying number of features provided in each browser version, client side interactivity testing is a must. The Dojo Toolkit’s own testing framework, nicknamed DOH (Dojo Objective Harness), is provided with each Dojo version download. Test writing is incredibly easy, and tests can be provided in a few different formats:

// Declare out the name of the test module to make dojo's module loader happy.
dojo.provide("my.test.module");

// Register a test suite
doh.register("MyTests", [
	// Tests can be just a simple function...
	function assertTrueTest(){
		doh.assertTrue(true);
		doh.assertTrue(1);
		doh.assertTrue(!false);
	},
	// ... or an object with name, setUp, tearDown, and runTest properties
	{
		name: "thingerTest",
		setUp: function(){
			this.thingerToTest = new Thinger();
			this.thingerToTest.doStuffToInit();
		},
		runTest: function(){
			doh.assertEqual("blah", this.thingerToTest.blahProp);
			doh.assertFalse(this.thingerToTest.falseProp);
			// ...
		},
		tearDown: function(){
		}
	},
	// ...
]);

The test above is a very basic example of a Dojo test, but what about a more difficult situation, i.e. asynchronous actions? The most obvious asynchrnous action is an AJAX request, but animations and other Deferred-powered actions will create such a situation. DOH provides an incredibly easy method for testing asynchronous actions using doh.Deferred objects:

{
	name: "Testing deferred interaction",
	timeout: 5000,
	runTest: function() {
		var deferred = new doh.Deferred();
		myWidget.doAjaxAction().then(deferred.getTestCallback(function(){
			doh.assertTrue(true);
		});
		return deferred;
	}
}

In the sample test above, the getTestCallback function doesn’t fire until doAjaxAction is complete, and returns the success or failure of the test.

The subsequent tests don’t move forward until the doh.Deferred resolves or times out, thus there are no test timing or overlap issues. DOH provides an incredibly reliable test suite that other client side frameworks simply do not provide. DOH also provides a Java-powered DOH robot which simulates real mouse and keyboard actions for more precise and realistic testing. If you hear Homer Simpson yell “Woohoo!”, all of your tests pass; if you hear that dreaded “DOH!”, your tests failed and you need to refactor your code.

DOH Resources


10. Dojo Build Process

When a web application is ready for release, it’s incredibly important, for the sake of optimized load and cacheability, to create a minified, layered JavaScript file or file(s). This reduces requests and keeps site load as light as possible. Better yet is that Dojo’s build system analyzes define calls and uses them to automatically detect dependencies for builds. To use the Dojo build process, you create what’s referred to as a build profile. Build profiles can contain numerous layers and may get quite complex, but the profile below is a simple example:

var profile = {
	releaseDir: "/path/to/releaseDir",
	basePath: "..",
	action: "release",
	cssOptimize: "comments",
	mini: true,
	optimize: "closure",
	layerOptimize: "closure",
	stripConsole: "all",
	selectorEngine: "acme",
	layers: {
		"dojo/dojo": {
			include: [ "dojo/dojo", "app/main" ],
			customBase: true,
			boot: true
		}
	},
	resourceTags: {
		amd: function (filename, mid) {
			return /\.js$/.test(filename);
		}
	}
};

Dojo’s build process is extremely customizable, allowing the developer to customize:

  • the minifier (Dojo’s ShrinkSafe or Google Closure)
  • the level of minification to be applied to the CSS files involved, if creating widgets
  • where the build is output to
  • the selector engine to be used within the build
  • …and much more!

Build profiles are run via the command line (recently rewritten for NodeJS), and the command line offers a variety of options to override or supplement settings within the build profile. A few examples of running the build profile include:

./build.sh --profile /path/to/app/app.profile.js --require /path/to/app/boot.js

The Dojo build process provides an incredible amount of control over the generated build files and rounds out the web application’s optimization process. With the CSS and JS minified and layered to appropriate levels, your Dojo-powered app is ready for showtime!


11. BONUS! “Dojo’s Treasure Chest”: More DojoX

Two very prominent DojoX libraries have already been mentioned above, DojoX Mobile and GFX, but those are only two of the dozens of hidden treasures provide by Dojo. Those treasures include:

  • extra layout and form widgets for Dijit
  • advanced, localized form validation routines
  • WebSocket and long-polling wrappers
  • image widgets, including lightbox, slideshow, and gallery utilities
  • advanced IO helpers
  • advanced drag and drop libraries
  • Nodelist extensions

These are only a few more of the dozens of gems within DojoX. Browse the Dojo checkout to find out more of the awesome fringe tools available!

The Dojo Toolkit is an all-encompassing JavaScript toolkit that provides:

  • Basic JavaScript language and helper utilities
  • Advanced Javascript language and AJAX utilties
  • On-demand asynchronous script loading
  • A complete UI framework
  • A comprehensive testing suite
  • Build tools
  • …and more!

Don’t start you next project without checking out all of the features Dojo has to offer! Even if you don’t need some of the advanced features listed above yet, using the Dojo Toolkit’s most basic features (element querying, animations, XHR requests) will get you well on your was to creating a fast, feature-rich web application with no ceiling!

Tags: dojo
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://okeowoaderemi.com Okeowo Omololu Remi

    As a big Fan of DojoToolkit i find it as my JavaScript Swiss Army, especially the Dijit UI, its so simple to create a Widget and extend that Widget and continue without duplicating codes, i was hoping to see Declarative Mark-up as one of the good reasons to use dojo cause it sheer amazing hoping to see 1.8/2.0 soon, however i must confess creating a Dojo Build is not exactly a walk in park especially reading the Reference Guide.

  • Jesus Bejarano

    Hoh is the David Walsh, is been long time since i saw you around netust+, good article.

  • http://www.permanaj.net Permana Jayanta

    Dojo is very good. Provide widget needed to create Backend, a complete solution. What I like most is Keyboard only navigation for the widget. But I still use jquery for the frontend as there are many cool stuff created by other developer.

    • keyboard_nav

      Keyboard navigation is already supplied by the browser for normal widgets. DOJO should be aiming to do what other libraries do…provide a thin layer on top of that instead of a thick layer of JS that is buggy and changes between versions. Keyboard navigation is not a real problem when a form is written in standard HTML and enhanced by JS rather than being written from the ground up in JS where support has to be explicitly provided, because for some reason your whole form has been taken over by spans and divs without any normal input properties.

  • Alter ego

    The one area where Dojo consistently fails for me is the documentation: it’s no good bringing the kitchen sink when no one can figure out how to use it.

  • http://inkwell.dotink.org Matthew J. Sahagian

    David, I love Dojo — unfortunately it’s very difficult for beginners. Not because the API is inherently bad, quite the contrary, I find it cleaner and more consistent than something like jQuery…. but the docs are still the major stumbling block I think for most people. Also, one thing that annoys me personally is how heavily the docs rely on attribute based dojo.

    Here’s some things I think would help:

    1. Create something similar to the jQuery/YUI rosetta stone (http://carlos.bueno.org/jq-yui.html)
    2. Show more programmatic examples, especially for Dijit
    3. Work to create some sort of resource for quality plugins or good working examples

    • http://superdit.com/ aditia

      yes agree with you, i’m giving up dojo cause lack of documentation, and how getting things done, one more dojo need to design more themes for its component

      • http://www.webhipster.com Vincent Young

        If you put in the effort it is well worth it.

    • respectfully_disagree

      > I find it cleaner and more consistent than something like jQuery

      I respectfully disagree. There’s a lot of jQuery stuff I don’t even have to consult the docs on because of the consistency of the platform. I write an event handler or anything else and it follows the same syntax and just works.

      DOJO has a very large consistency problem, and it’s not just because of beginners. DOJO doesn’t take the idea of enhanced HTML to heart, they often require declarative widget building leaving things like progressive enhancement in the dust. DOJO’s core widgets don’t even work out of the box in their demos, and there’s still things that echo out “experimental API that may be subject to change” when you’re on a major release of the library.

      DOJO is too big, and attempts to do too much to be consistent with itself.

      HTML is becoming a more defined language. It is becoming easier everyday to achieve things with HTML + CSS that were only possible with JavaScript in the late nineties and the 00s. DOJO does not seem to be following this trend, and instead of adding less JS layer on top of the HTML to get things functional, they continue to add more and more needless mess.

      Altering the widgets to make them fit even the simplest use cases that were outside of the primary example is a chore. I was attempting to simply make a BusyButton stop showing as busy when an AJAX request completed (instead of the insane default of a timeout on the button….what!?) and there was nothing to be found in any doc about this. I had to read through a DOJO mailing list post to figure out that you call widget.cancel() (which, btw, also isn’t what I would expect that to be called intuitively).

      • Philippe Soares

        > “HTML is becoming a more defined language. It is becoming easier everyday to achieve things with HTML + CSS that were only possible with JavaScript in the late nineties and the 00s”

        Well, I use dojo for an enterprise application, and I have customers that are still under IE 7 or 8… I don’t see myself using plain HTML + CSS in my app, and deal with browser inconsistencies myself. I also can’t see how I would do ajax with just HTML + CSS.

        > “I was attempting to simply make a BusyButton stop showing as busy when an AJAX request completed (instead of the insane default of a timeout on the button….what!?) and there was nothing to be found in any doc about this”

        Well, I can’t see the point of the timeout either, but I think the purpose of that widget is only to prevent double form submission. However, as you said, that specific widget has a “cancel” method and its counterpart “makeBusy”. That is documented in http://dojotoolkit.org/api/. Just follow the path to your widget and check the “methods” section. No need for any mailing list here… Now for your real use case, which is “how do I monitor an ajax request”, you should read http://dojotoolkit.org/documentation/tutorials/1.8/ajax/ and http://dojotoolkit.org/reference-guide/1.8/dojo/promise/Promise.html#dojo-promise-promise.

        You’ll see that achieving your desired behaviour is just a matter of : request(“some/url”).always(function(){ myButton.cancel(); });

  • Some Guy

    I have no idea what I just read.

    • http://www.webhipster.com Vincent Young

      Some Guy,

      Could you explain further. Commenting, “I have no idea what I just read”, is very uninformative.

      Thanks.

      - Vincent

  • http://uxinnovator.com Kenton

    I would have to argue that ExtJS is the most powerful JS utility if you call Dojo an utility.

    • http://freebiesdesign.com Keven

      Yes i agree with that!

    • http://twitter.com/monteslu Luis Montes

      Could you give some examples of things you can do with ExtJS that you can’t with dojo?

    • mpmedia

      the problem with ExtJs is the license. It may be good but for me the license is a no go.

      • http://www.akawebdesign.com Arthur Kay

        What’s wrong with Sencha’s license? That it’s not “free” for commercial use?

    • http://willcode2surf.wordpress.com willcode2surf

      hmmmm. ExtJS comes with licensing challenges and there might be some $$$ involved. Plus, I have never seen something done with ExtJS that warranted us purchasing some enterprise software written in it. once we saw what dojo was doing our focus quickly became HTML5 and friends quickly. and utility is a broad term. this is a TOOLKIT.

  • http://dojotoolkit.org Tom Trenka

    One small comment to make: with dojo/_base/declare, the first argument (in this example, “mynamespace.CustomButton”) is actually optional–because declare will return the declared constructor.

    For examples of anonymous declarations, take a look at the repository for dgrid, which David talks about above.

  • Me, myself and I

    I’m a big fan of Dojo. But it is a shame that is have not the same quantity of jQuery plugins, not even close.
    I hate the spaghetti code; but it is hard to sell to a client comprehensiveness over ease of use (dojo and jquery respectively).

    One question. How can I achieve MVC on Dojo in a way comparable to Backbone?.

    Thanks for the tutorial. Excellent job!

    • mpmedia

      MVC is an idea , and not even a design pattern. Backbone doesnt follow a “MVC” architecture neither ,so what is the problem ? Avoiding spaghetti code is about decoupling and separation of concerns. You dont need a framework for that.

      Furthermore , you can use Dojo and Backbone together , like you can use jQuery in Backbone views , i dont see any problem here.

      • Me, myself and I

        Thanks for your thoughts :)

    • http://willcode2surf.wordpress.com willcode2surf

      There are some great tutorials on the dojotoolkit.org site that discuss how this is accomplished (MVC) and actually show you how to do it.

      I agree on the plugins but thats the beauty of dojo, you can extend their code and build dijits rather easily. There is a few tutorials that show how this is done too.

      So, the answer to a lack of bad ass plugins is the dojo community of developers that just need to step up and contribute to their project.

  • http://www.alphavega.com lord xeon

    I’m gonna have to disagree with you on points 5 & 7.
    I work on an Enterprise level application that uses Dojo extensively, and over the year’s I’ve been here, I’ve gotten pretty well versed in it I would think.

    5. Dijit UI Framework
    It’s nice in the aspect that you have access to hundreds of different widgets that more or less work out of the box.
    But it is a styling nightmare.
    I mean no disrespect for the Dojo Team, but they don’t know CSS. JavaScript they have down expertly, but they need alot of help with their CSS. I’m not talking about a theaming standpoint, I’m talking from a purly layout view. The CSS is a mess. And if you want to change the styles of buttons, or tabs, you have to have gigantic selector chains and/or judicial use of the !important flag, not nice.
    Also the class names used.

    .dijitButtonContents {}
    .dijitDownArrowButton {}

    I get that you want to namespace them, but you can do that through the natural inheritance of CSS:

    .dijitButton .arrow.down {}

    (Maybe this has changed in 1.7, since my company is stuck on 1.5/1.6 and it will cost far too much to upgrade to the drastic change that 1.7 made,(which should have been 2.0 if using semantic versioning))

    7. GFX and Charting
    Dojo has a nice charting library, but compared to some other ones, it’s overly complex, convoluted, and bloated.
    I’ve worked with the Dojo charting library, HighCharts, flot, and d3.js. And d3 is hands down the best data visualization tool I have ever used. It’s simple and intuitive and powerful.

    • Okeowo Aderemi

      Well I think the class names are justified, with those type you mentioned its pretty easy to get overriding styles from another css with names like “arrow or down”.

  • http://sethmohit.com Mohit Seth

    I haven’t used Dojo ever but reading gives me a reason to try. I think everything is included 1 single package. Right now, I use requirejs for implementing AMD. I also like deferred which was introduced in jQuery after 1.5. Since then I started using it and I love it. The build process is also similar to requirejs. I will give a try to Dojo in some test project. I am only concerned about the performance of dojo. Normally such kind of suite have performance issues like ExtJS.

  • mpmedia

    jQuery – Dojo – ExtJs – etc …
    where all these frameworks fail is on mobile , too big , poor performances , too resource hungry , even on good handsets. That’s why customers prefer native apps , until javascript engines get as performant as on desktop or these libraries are coded with mobile capabilites on mind, it’s quite hard to recommand any of them.

    • http://okeowoaderemi.com Okeowo Omololu Remi

      i slightly agree with you but the performance is not as terrible as u make it seem, i achieve optimal speed on the Android and IOS and even the Playbook, the only place with poor performance is the Blackberry OS6 and below,

    • Brian

      Ext JS is not a mobile framework — that’s what Sencha Touch is for (http://www.sencha.com/products/touch/). As far as web app performance on mobile goes (which of course will always be slower than native) it’s about the best there is.

      jQuery and jQuery Mobile are also separate libraries as well.

  • http://blog.pathtosharepoint.com Christophe

    If I had never used it, I would find dojo really exciting after reading your article. Unfortunately, I have been experimenting with dojo for a couple months and it’s been a series of disapointments. Tooltip that doesn’t work (quickly replaced with jQuery qtip2 installed in a snap), demos that don’t work on the dojo site itself (e.g. Gantt in v1.7.2), blog comments that are not published (and even less answered), only framwework of this size that doesn’t have a decent forum… that’s a lot of obstacles on the way.

    I have not given up though, and I’m looking forward to v1.8 (the release was expected last month…).

    • Name

      Exactly my experience. I can more easily get a jQuery widget working within DOJO than I can get a DOJO widget working within DOJO.

  • http://defaulttricks.com Mohit Bumb

    How to use dojo ??

  • http://jspeaks.com Jaye Speaks

    I preface my comments with respect for David Walsh, Dylan Schiemann, and all the other people that contribute to helping people with JavaScript, and pioneering in JavaScript. I also profoundly respect that Dojo Toolkit has the honor to claim some of the earliest JavaScript library work as seen in this History of JavaScript Timeline. That being said…

    I don’t agree that projects should use the Dojo Toolkit. Here is why:

    You can’t find enough people experienced or skilled to assist

    I watch incoming projects on the online project marketplaces. The incoming project inventory is one indicator that Dojo is rare. Interaction with recruiters is another. Dojo Books are ancient.

    Once you code in Dojo for a year (like I have) you discover a lot of things you wished were different

    Dojo documentation is a PIA. Reading the Dojo code is the only real solution. Debugging is a PIA. Firebug usually outputs obfuscated ;)) error messages.

    I have many other reasons!

    Dojo is function centric when leveraging core features, ugh

    I prefer the jQuery style of chaining, and everyday I code in Dojo I yearn for it. The function style of appending items to DOM nodes, and hitching this everywhere is just very tedious.

    Conclusion

    I suggest that if you want an advanced JavaScript framework you would be better off building with ExtJS, however I have leveraged the simplicity and power of RequireJS, jQuery, and Backbone in the past and I discovered they are sufficient to build amazing applications. Those JavaScript tools are more modern, have enhanced patterns of usage, are more predominant, and are more than sufficient to be the basis of a new project.

    • http://blog.pathtosharepoint.com Christophe

      Sure, you can do a lot with RequireJS, jQuery and Backbone. Then you can add a charting library (D3?) and a grid (Datatables?) to start building business applications. Maybe a couple plugins too, because you’ll want stuff like tooltips. You’ll end up with half a dozen libraries, and it’ll be up to you to deal with versions and build your own testing framework.

      As for your main argument, the lack of skilled people, you could certainly have said the same about jQuery 5 years ago. I am afraid things are moving very fast, and the present doesn’t tell us much about what the landscape will look like in 3 years.

      I am certainly not a fan of dojo (cf. my earlier comment), but I definitely see a window of opportunity here.

    • Strangepants

      +1 regarding the Dojo documentation

  • http://Estejs.tumblr.com Daniel Steigerwald

    Hi David, just a note. If you are talking about best library, do not forget about Google Closure. It’s something like polished Dojo, with unbeatable compiler. Nothing can beat Closure, except my Este.js ofc :-)

  • Sam Foster

    Great article and interesting comments. I think there has long been consensus about the importance of documentation and I’m really glad to see this has been a priority in the latest release: http://dojotoolkit.org/blog/dojo-1-8-released

    Another issue highlighted above was the debugging experience. The move to AMD and async loading (1.6 to 1.7 – i.e. over a year ago) has made that *much* better. Its the same experience as if you’d manually written all those script tags into your document yourself – good filename links and line numbers, break points break at the right place etc.

    Of the other vague grumblings about Dojo, yes of course its not perfect. There are some dusty corners and murphy’s law says that the first complex thing you try to do will be something no-one else has needed yet. And its a large toolkit, and TMTOWTDI (there’s more than one way to do it) and all the good and bad that implies.

    But David is bang-on to call out some of the pioneering Dojo has done. Not just as a “Dojo did that first” crowing, but because some of these concepts have been in use for so long, good patterns permeate the whole toolkit in a way that makes whole classes of problems just go away.

    Of course, problems not encountered are rarely remarked upon, so take it all with a pinch of salt and try it for yourself on your next project.

    As for MVC and architectural patterns, take a look at the TODOMVC project and compare/contrast the Dojo, Backbone and other implementations in there. You might like it.

    • kill_the_complexity

      My main problem with DOJO is that it has enough breadth to get dusty. When you look at jQuery, it’s basically a thin wrapper on the existing DOM. All modern JS libraries follow that same pattern (with DOJO as the exception to the rule).

      DOJO needs to lock its core down and make it smaller instead of modularizing every single function to the point where you need an AMD block with 14 variables in it to do anything useful.

      I understand that this may cause some pain in the upgrade cycle. May I raise the idea of a DOJO lite with a broken upgrade path?

      jQuery has nailed the implementation of this. Their core library contains almost everything you need to get up and running and building a quick JS app.

      If DOJO wants to be serious, they have to not only do more about the docs (the docs still pale in comparison to jQuery despite the newfound focus on them), they have to do something about making the platform consistent and easily usable. Most DOJO examples for new widgets have major rendering problems or simply don’t work, and those examples are hundreds of lines of code more complex than they need to be. DOJO has made the app I’m writing so complex that in order to move away from coupling myself on it, I’ve gone back to simply writing JS blocks.

  • Travis Anderson

    One look at the Dijit UI stuff turns me off. Dear God, that is some ugly, ugly markup. The dropdowns use tables, bleh. I would hate styling that. I agree with the comment above, these guys are way out of touch with css AND markup.

    Overall some nice concepts, Dojo seems cool, but the jQuery community is making many positive strides in most of these areas.

    Can’t put my finger on it, but something about Dojo just feels dated. It’s just old school vs new school, and in the open source world I want to be using things that other others are passionate and excited about, and bringing fresh energy to.

    • Chas

      In my view, Dijit widgets are aimed mostly at enterprise that need a form-centric UI, and they are very well adapted to that. Comparing them to the common way/projects where one would work with jQuery is not an relevant/interesting comparison IMHO: In reality, you’d usually use them for projects that are quite different.

      Believe me, if you’re building an enterprise app where complex forms are the main issue, Dijit is very attractive.

      • enterprisey

        I really think that the whole idea of the term “enterprise app” is to pretend that things need to be more complicated than they are in reality. Hearing that DOJO is JS for the “enterprise apps” makes me think of EJBs and all the other places where “enterprise technologies” really just meant stuff that didn’t work at all, worked poorly, or only worked in the single way it was originally coded for.

        I’ve been using DOJO for an “enterprise app” for some time now, and I have to say, even with complicated forms I think jQuery is a better fit. The reason jQuery is a better fit is because it gives you building blocks and allows you to build your “enterprise app” with them. To me, enterprise shouldn’t mean a solution that has to work one way, it should be about scalability or ease of building. DOJO provides neither of those things. The documentation is outdated and in some cases non-existent for the simplest customizations to their built-in widgets. In addition, it’s slow, it loads dozens upon dozens of JavaScript files to do the simplest tasks (because I know…each thing is a module or whatever).

        I have seen nothing that makes me think that DOJO is better for enterprise or anything at all to be honest. I’ve used prototype.js in its heyday, and I have to say that that even seems like a more modern library (today) than DOJO does.

      • http://www.facebook.com/SystemECKS Alexander-Edward Powell Caskey

        working on an enterprise dojo app makes me agree with the attraction. It’s actually incredibly simple to use quite powerful features in dojo. Although I was never a fan until i got stuck in one day and made a website in a couple of hours using a few widget katas, and it was really quite nice and flashy, and I had complete control.

        And anyone not experienced in dojo, can be ramped up in a few days, and then learn the more advanced things later on, just like I did. The only thing that would impede this is a lack of understanding of javascript, or any unwillingness to use the toolkit. I personally jump at the chance to make JS more OO, that just makes my life 100x better.

        Sounds to me like travis didn’t have his browser settings to allow the dojo markup. The claro theme (and others) is very slick, and positively reinvents many of the generic form elements.

        However, this was 9 months ago. I’m sure now with dojo1.8 everyone will have different opinions

  • http://www.javaexperience.com/ Java Experience

    using dojo, one can also add busy loader which blocks access to UI till the time the Ajax requests get completed.

  • Rooter

    I work on Dojo in an enterprise environment. I do respect all of the original developers and appreciate that it once led the way in web application innovation. Unfortunately in it’s current form the framework is a confused and bloated mess. Apart from a dying breed of Dojo die-hards, is is common consensus that the tool-kit provides an inherent lack of abstraction, and offers zero consistency in providing a basic application architecture. The web has moved on, anyone thinking of using Dojo should do the same.