Download - Dojo Quickstart
-
7/29/2019 Dojo Quickstart
1/32
Why Dojo?
The Dojo Toolkit is an open-source JavaScript toolkit useful for building great web
applications. It aims to shorten the timespan between idea and implementation
by providing an exceptionally well conceived API and set of tools for assisting andfixing the issues experienced in everyday web development. It is lightning fast,
extremely robust, and supplies a solid set of tools for DOM manipulation,
animations, Ajax, event and keyboard normalization, internationalization (i18n)
and accessibility (a11y). Dojo Base is a single, lightweight 26KB entity "across the
wire." Dojo is completely free, liberally licensed (AFL or BSD), and transparently
developed by an active group of developers with a strong community presence.
No matter the size of your projects, Dojo is the ultimate scalable solution to your
development woes. The built-in package system ends the headache of tracking
dependencies, the build system combines and shrinks optimized "layers" of code
for deployment, and D.O.H. makes unit and regression testing a breeze.
The add-ons.
In addition to all the great tools available in the Base dojo.js, using the powerful
package system, you can add functionality to your application through
simple dojo.require() calls. Dojo Core includes great tools such as drag and
drop, advanced Ajax transports, string utilities, a powerful data API, and hundreds
of others to use to easily make exceptional rich internet applications.
Endless possibilities.
The Dojo Toolkit also comes pre-packaged with a project called Dijit, a system for
using and creating encapsulated, reusable components or widgets. The system
provides accessible, extensible, themeable components to drop into your web
applications and sites, and a solid API for streamlining the development ofyour
own widgets or customizing the behavior of existing widgets.
Cutting edge technology
With Dojo, many of the latest and greatest technologies are at your fingertips.
Buzz words like Web 2.0, Ajax, and Comet provide a great starting point to
describe the experience you'll be creating. dojox.gfx, dojox.charting and Dojo
Offline quickly go beyond the hype, pushing the limits of the web experience to
new heights.
http://www.sitepen.com/blog/2007/11/02/html-widget-prototyping-with-the-dojo-toolkit/http://www.sitepen.com/blog/2007/11/02/html-widget-prototyping-with-the-dojo-toolkit/http://www.sitepen.com/blog/2007/11/02/html-widget-prototyping-with-the-dojo-toolkit/http://www.sitepen.com/blog/2007/11/02/html-widget-prototyping-with-the-dojo-toolkit/ -
7/29/2019 Dojo Quickstart
2/32
Getting The Code
Download the newest released version of the Dojo Toolkit
from: http://download.dojotoolkit.org/
The "built" version is: dojo-release-1.3.0.zip
Unpack the contents of the archive into a folder (preferably on a web server as
this is always a good case for Ajax development). Let's call it "js/". You may also
name your dojo directory "dojotoolkit" as the examples here will show. If you wish
to version Dojo, you may leave it as dojo-release-1.3.0. You should now have a
directory structure similar to this:
The most important thing to know when installing the Dojo Toolkit is where your
copy ofdojo.js is located. The package system handles the loading of all other
dependencies and modules, once dojo.js has been loaded into the page.
You can verify your download and install is working by pointing your web browser
tohttp://localhost/js/dojotoolkit/dojo/tests/runTests.html or browse
the dijit test pages at http://localhost/js/dojotoolkit/dijit/tests/
The Dojo Book, a freely available collection of guides and tutorials, provides a
more in-depth description of the various ways to get the Dojo source and
about the different releases available.
First Steps
Start by making a skeleton HTML file for use as a basic template for any example:
Dojo Toolkit Test Page
http://download.dojotoolkit.org/release-1.3.0/http://dojotoolkit.org/book/dojo-book-0-9/part-1-life-dojo/quick-installationhttp://download.dojotoolkit.org/release-1.3.0/http://dojotoolkit.org/book/dojo-book-0-9/part-1-life-dojo/quick-installation -
7/29/2019 Dojo Quickstart
3/32
/* our JavaScript will go here */
/* our CSS can go here */
Dojo Skeleton Page
Some Content To Replace
This page has a DOCTYPE of "HTML/4.01 Strict", and almostpasses W3Cvalidation. This can be fixed, but the shorthand is convenient. You will learn about
both valid and convenient methods in this guide.
Configuring Dojo
-
7/29/2019 Dojo Quickstart
4/32
Dojo has a mechanism for setting various configuration options at runtime. The
two most common are parseOnLoad, which toggles page-load parsing of widgets
and in-markup code, and isDebug, which enables or disables certain debugging
messages.
Conveniently, you can set these options directly in the tag
that loads indojo.js via a custom attribute named djConfig. Simply modify the
skeleton HTML template to add the new attribute:
If the above validation concerns you (you know who you are), you can setup a
global djConfig variable before dojo.js is loaded:
var djConfig = {
isDebug:true,
parseOnLoad:true
};
Both examples have the same effect.
When can I start?
As soon as the document is ready and loaded...
There are a number of cross-browser differences in defining "ready", so to aid inyour continued sanity, Dojo has a method of executing code when the document
is really "ready":dojo.addOnLoad. Everything we do that could possibly affect
the DOM should be started by passing dojo.addOnLoad a function:
// a very common method of loading code onLoad
var init =function(){
-
7/29/2019 Dojo Quickstart
5/32
console.log("I run after the page is ready.");
};
dojo.addOnLoad(init);
// and/or pass an anonymous function
dojo.addOnLoad(function(){
console.log("I also run, but second. ");
});
dojo.addOnLoad is a fundamental aspect of using Dojo, and is very important to
remember. Without it, you cannot be sure all the necessary content has been
loaded before your own code begins to execute.
It's important to note that you should notset on onLoad function directly on
the tag when using dojo. dojo.addOnLoad(someFunc) is prefered
over and window.onload = someFunc;
More than just dojo
Dojo has a package system built in to load all the code you need, controlled
bydojo.require(). This function allows us to pull in parts of the Dojo Toolkit not
provided for in the Base dojo.js, such as Drag and Drop, additional animations,
dijit widgets, dojox projects, or even your own code.
For example, to load the code needed to use the TitlePane widget, and a Dijit
Button into your page include the
modules dijit.TitlePane and dijit.form.Button:
dojo.require("dijit.form.Button");
dojo.require("dijit.TitlePane");
dojo.addOnLoad(function(){
dojo.byId("testHeading").innerHTML ="We're on our way!";
console.log("onLoad fires after require() is done");
-
7/29/2019 Dojo Quickstart
6/32
});
Each "module" has it's own dojo.require()'s, and knows not to load code it
already has. Code executed by dojo.addOnLoad doesn't run until after
your dojo.require()'s are all finished loading, making it that much safer and
convenient to use.
A full list of available widgets and the module they live in can be found at theDijit
API pages, or explored by browsing the dijit/tests/ folder that came with your
download.
Moving on
In the last example, we snuck a very common method into our addOnLoad
code: dojo.byId(). This returns the domNode of an element by
its id attribute. dojo.byId() is a convenient way to access a specific node, and
manipulate it. Here we're changing the text of the heading in the body, through
its .innerHTML property.
If all you see is "We're on our way", you really are on your way to some really
interesting web development: dojo.bliss. If you are experiencing errors,
something has gone wrong. A lot of common mistakes are covered in the FAQ,
available at the Dojo Toolkit website.
DOM Magic
A really nice tool Dojo provides is dojo.query. It's a great way to parse all or
portions of the Document Object Model (DOM) and access selections of nodes. It
really deserves its own book. Each of the following sections will touch on how to
use dojo.query more closely, though realizing its potential is as simple as seeing
it used:
dojo.require("dojo.NodeList-fx");
dojo.addOnLoad(function(){
// our dom is ready, get the node:
dojo.query("#testHeading")
.addClass("testClass") // adds class="testClass"
.fadeOut({ delay:500 }).play(); // and fade it out after 500ms
http://api.dojotoolkit.org/jsdoc/dijit/1.2/dijithttp://api.dojotoolkit.org/jsdoc/dijit/1.2/dijithttp://api.dojotoolkit.org/jsdoc/dijit/1.2/dijithttp://dojotoolkit.org/support/faqhttp://dojotoolkit.org/support/faqhttp://api.dojotoolkit.org/jsdoc/dijit/1.2/dijithttp://api.dojotoolkit.org/jsdoc/dijit/1.2/dijithttp://dojotoolkit.org/support/faq -
7/29/2019 Dojo Quickstart
7/32
});
Add .testClass CSS definitions to set color:red; and your heading will get that
style before fading out.
.testClass {
color:#ff0000;
}
dojo.query returns an instance of a dojo.NodeList, a synthetic super-Array of
domNodes. It supports most CSS3 selectors (so you can go really wild with its
syntax), and execute code against the whole list of results. To demonstrate this,
we're going to need something more than a single heading, so add some content
to our DOM:
Dojo Skeleton Page
First link
Second Link
First paragraph
Second paragraph
Third paragraph
And use a different query:
dojo.require("dojo.NodeList-fx");
dojo.addOnLoad(function(){
// get each element with class="para"
dojo.query(".para")
.addClass("testClass")
.fadeOut({ delay:1000 }).play();
http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/selecting-dom-nodes-dojo-query/attribute-queryhttp://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/selecting-dom-nodes-dojo-query/attribute-query -
7/29/2019 Dojo Quickstart
8/32
});
All three
elements should turn red, and fade out after a second delay. The full
list of thingsdojo.NodeListdoes is impressive, some of which we'll touch on in
later sections of this guide.
Most dojo.query chains have standalone functions to achieve the same goals.
For
instance:dojo.query("#testHeading").addClass("testClass"); anddojo.a
ddClass("testHeading","testClass") have identical results.
Events
The next important concept we are going to cover is interacting with our page.We've already set the heading to some alternate text, but what if we wanted to
so something more interesting? Perhaps change it to something else when the
user clicks on it? dojo.connect is the one-stop solution for all your event needs:
dojo.addOnLoad(function(){
var node = dojo.byId("testHeading");
dojo.connect(node,"onclick",function(){
node.innerHTML ="I've been clicked";
});
});
A convenient way to do the above using dojo.query would be:
dojo.addOnLoad(function(){
dojo.query("#testHeading")
.style("cursor","pointer")
.connect("onclick",function(){
this.innerHTML ="I've been clicked";
});
http://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.NodeListhttp://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.NodeListhttp://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.NodeList -
7/29/2019 Dojo Quickstart
9/32
});
We added another chain .style to our example, to make the cursor a pointer
when hovering over the header node. We could have done this with plain CSS,
and probably should have, to avoid unnecessary code. This, however, is aconvenient way to dynamically alter most any CSS property, and very useful.
This allows us to make an onclick function on more than one node at a time,
though our NodeList only has one element above. We could easily find a big
group of elements, and affect them all. For instance, to prevent all links on a
page from leaving, utilize the normalized eventobjectdojo.connect passes:
var disableLinks =function(){
dojo.query("a").connect("onclick",function(e){
e.preventDefault(); // stop the event
console.log('clicked: ',e.target); // the node weclicked on
});
};
dojo.addOnLoad(disableLinks);
The code e.preventDefault will prevent the event from "doing what it was going
to do". In the example, we preventDefault on the click event, which would have
followed the anchor link we connected to. It is common to see the eventobject
written as e or evt when passed as a paramter.
More about the normalized eventobject used in Dojo can be found in the Event
Object Book Page at the Dojo website.
We can also connect to methods of specific objects, and execute them in the
same scope. This is useful as you get into declaring classes in Dijit, or animations.
Lets create a really simple object with some methods, and watch them interact:
var mineObj = {
aMethod:function(){
http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/event-system/event-objecthttp://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/event-system/event-objecthttp://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/event-system/event-objecthttp://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/event-system/event-object -
7/29/2019 Dojo Quickstart
10/32
console.log('running A');
},
bMethod:function(){
console.log('running B');
}
};
var otherObj = {
cMethod:function(){
console.log('running C');
}
};
dojo.addOnLoad(function(){
// run bMethod() whenever aMethod() gets run
dojo.connect(mineObj,"aMethod",mineObj,"bMethod");
// run an entirely different object's method via a separate
connection
dojo.connect(mineObj,"bMethod",otherObj,"cMethod");
// start chain of events
mineObj.aMethod();
});
You should see "running A B C" on separate lines in the console. The full power
ofdojo.connectcan be explored via the dojo.connect API, or in the Events
chapter of the Dojo Book.
Some Gloss: Dojo Animations
http://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.connecthttp://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/event-systemhttp://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/event-systemhttp://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.connecthttp://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/event-systemhttp://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/event-system -
7/29/2019 Dojo Quickstart
11/32
Dojo has a powerful animation system with several pre-made animations for a lot
of common use cases. Adding some visual flair to you projects has never been
easier, and typically makes the users experience a lot more interesting.
All animations use a single "magic object" as it's only parameter. The most
important being thenode:attribute, the domNode on which to apply our
animation. Some parameters are optional, and some are for advanced usage. A
common setup would look something similar to:
dojo.addOnLoad(function(){
var animArgs = {
node:"testHeading",
duration:1000, // ms to run animation
delay:250// ms to stall before playing
};
dojo.fadeOut(animArgs).play();
});
Base Animations:
Animations included in basedojo.jsare: fadeIn, fadeOut, and
animateProperty.dojo.animatePropertyis very powerful, and is the foundation
for most advanced animations, and other animations in Dojo Core.
dojo.addOnLoad(function(){
dojo.style("testHeading","opacity","0"); // hide it
var anim1= dojo.fadeOut({ node:"testHeading", duration:700 });
var anim2= dojo.animateProperty({
node:"testHeading", delay:1000,
properties:{
// fade back in and make text bigger
opacity: { end:1 }, fontSize: { end:19, unit:"pt"}
-
7/29/2019 Dojo Quickstart
12/32
}
});
anim1.play();
anim2.play();
});
As seen,dojo.animatePropertywill fade the element back in via
it'sopacityproperty, and simultaneously make the text larger. You can animate
most any CSS property this way.
In JavaScript, when modifying multi-word properties such asfont-
sizeandborder-top, you must use a mixed cased version, as hypens are
illegal as keys. UsefontSizeandlineHeight, instead offont-sizeorline-heightfor example.
Additional FX
A lot can be done visually with the base animations, animateProperty especially.
To keep the size of the basedojo.jsdown, all the additional animations and
tools have been packaged into a single module:dojo.fxto be optionally called
in viadojo.require. Adding the module to your code provides several additional
animation methods:dojo.fx.combine, dojo.fx.chain, dojo.fx.wipeIn,dojo.fx.wipeOutanddojo.fx.slideTo.
dojo.require("dojo.fx");
dojo.addOnLoad(function(){
// slide the node to 75,75
dojo.fx.slideTo({
node:"testHeading",
top:75, left:75
}).play(); // and play it
});
-
7/29/2019 Dojo Quickstart
13/32
dojo.fx.chainanddojo.fx.combineare very useful, too. They run animations
in parellel or in sequence, returning a single instance ofdojo._Animationto use:
dojo.require("dojo.fx");
dojo.addOnLoad(function(){
var anim = dojo.fadeOut({ node:"testHeading" });
var anim2= dojo.fadeIn({ node:"testHeading" });
dojo.fx.chain([anim,anim2]).play();
});
Combining an animation to fade in and out wouldn't make sense, so lets fade it
out and slide the node simultanously usingdojo.fx.combine:
dojo.require("dojo.fx");
dojo.addOnLoad(function(){
var anim = dojo.fadeOut({ node:"testHeading" });
var anim2= dojo.fx.slideTo({ node:"testHeading", top:75,left:75 });
var result = dojo.fx.combine([anim,anim2]);
result.play();
});
Animation Events
Eachdojo._Animationhas a series of "events" to tie into for more advanced
usage. Going back to the one-stop-event-shopdojo.connect, we can connect to
specific actions of the animation, and do other things. The most common
areonEndandbeforeBegin.
dojo.addOnLoad(function(){
var anim = dojo.fadeOut({ node:"testHeading" });
dojo.connect(anim,"onEnd",function(){
-
7/29/2019 Dojo Quickstart
14/32
console.log(" the animation is done ");
});
dojo.connect(anim,"beforeBegin",function(){
console.log(" the animation is about to start ");
});
anim.play();
});
These events are espeically helpful when you want to do things like change some
content out while a node is hidden and then fade it back in:
dojo.addOnLoad(function(){
var anim = dojo.fadeOut({ node:"testHeading" });
dojo.connect(anim,"onEnd",function(){
dojo.byId("testHeading").innerHTML ="replaced afterfade!";
dojo.fadeIn({ node:"testHeading" }).play();
});
anim.play();
});
Conveniently, you can pass the event functions as properties to the animation.
Usingdojo.connectto setup the functions gives us a lot more power, and are
typically safer for advanced uses, but sometimes it's easier to wrap it all in:
dojo.addOnLoad(function(){
var anim = dojo.fadeOut({
node:"testHeading",
onEnd:function(){
dojo.byId("testHeading").innerHTML ="replaced ... ";
-
7/29/2019 Dojo Quickstart
15/32
dojo.fadeIn({ node:"testHeading" }).play();
}
}).play();
});
The full explanation of events is available at thedojo._AnimationAPI pages.
animateProperty
Probably the most powerful of the base
animations,dojo.animatePropertyallows us to easily animate multiple css
properties simultaneously.
Since animateProperty is adojo._Animation, it uses the same arguments as
other animations. With an additonal object,propertieswe can define any style
property of a node. Fromstarttoend, and optionally using aunitattribute.
Manipulating our header element to use a new font color, size, and overall
opacity is as easy as:
dojo.addOnLoad(function(){
var anim = dojo.animateProperty({
node:"testHeading",
duration:700,
properties: {
// javascript css names are camelCase
// (not hyphenated)
fontSize: { start:12, end:22, unit:"pt"
},
opacity: { start:1, end:0.5 },
color: { start:"#000", end:"#FFE" }
},
delay:100// Note! trailing commas break IE.
http://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo._Animationhttp://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo._Animation -
7/29/2019 Dojo Quickstart
16/32
});
anim.play();
});
dojo.query Animations
Dojo provides another convenient module:dojo.NodeList-fx, which adds
additional methods todojo.queryfor the availabledojox.fxanimations. To
enable these methods, simply add in the required module:
dojo.require("dojo.NodeList-fx");
dojo.addOnLoad(function(){
dojo.query("#testHeading").fadeOut().play();
});
The above gives us the same effect as callingdojo.fadeOutdirectly,
butdojo.queryhere makes an animation for each of of the NodeList elements,
and combines them into a singledojo._Animation. This can be useful when you
have groups of like nodes you want to easily affect (in this case, all the nodes
withclass="fadeNode").
dojo.require("dojo.NodeList-fx");
var fadeThem =function(){
dojo.query(".fadeNode").fadeOut().play();
}
dojo.addOnLoad(function(){
dojo.connect(dojo.byId("testHeading"),"onclick","fadeThem");
});
Unlike other dojo.query() chains, the NodeList-fx methods return an instance
ofdojo._Animation, preventing further chaining.
-
7/29/2019 Dojo Quickstart
17/32
Ajax: Simple Transports
Ajaxis an acronym for "Asynchronous JavaScript and XML", a technology
employed to send and receive data on the fly. It can be used to update sections
of a website from any number of remote sources, send data to the server and
pass responses back and forth, all without ever refreshing the webpage.
Having been versed on some essential Dojo methods, we'll move on the the
bread and butter of Ajax: XmlHttpRequest (or XHR for short). Dojo has several
XHR methods available using common HTTP verbs:POST, GET, PUT, and
DELETE.
To prepare, we need to create a file with some text to load in. Create a file
namedsample.txtin yourjs/folder with sample text:
I am a remote file.
We used Ajax to put this text
in our page.
And modify theskeleton.htmlto have some basic markup and style:
#container {
border:1px dotted#b7b7b7;
background:#ededed;
width:75px;
height:55px;
}
I am some Inner Content.
I am going to be replaced
-
7/29/2019 Dojo Quickstart
18/32
The XHR methods usedojo.Deferredbehind the scenes to handlecallbacks.
This is beyond the scope of a QuickStart, but extremely useful in practice. Ifyou would like to learn more about callbacks and the various way to set them
up, visit theDojo bookor thedojo.DeferredAPI pages.
Getting data
The first stepping stone isdojo.xhrGet, which will return the contents of a GET
call on a URL. The XHR methods share a lot of common parameters. Most
important are theurl:(our destination) andhandleAs:(how we handle what is
coming back). When the data arrives, it will be passed the theload:function wedefine:
var init =function(){
var contentNode = dojo.byId("content");
dojo.xhrGet({
url:"js/sample.txt",
handleAs:"text",
load:function(data,args){
// fade out the node we're modifying
dojo.fadeOut({
node: contentNode,
onEnd:function(){
// set the data, fade it back in
contentNode.innerHTML = data;
dojo.fadeIn({ node: contentNode }).play();
}
http://www.dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/miscellaneous/communication-between-threads-dohttp://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.Deferredhttp://www.dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/miscellaneous/communication-between-threads-dohttp://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.Deferred -
7/29/2019 Dojo Quickstart
19/32
}).play();
},
// if any error occurs, it goes here:
error:function(error,args){
console.warn("error!",error);
}
});
};
dojo.addOnLoad(init);
You will notice we've combined techniques above. The content will fade out, be
replaced by the received data, and fade back in using methods we've learned to
this point. It was almost too easy.
A singlehandleargument can be used instead ofloadanderror, handling both
success and failure cases in a common function:
var init =function(){
dojo.xhrGet({
url:"js/sample.txt",
handleAs:"text",
handle:function(data,args){
if(typeof data =="error"){
console.warn("error!");
console.log(args);
}else{
// the fade can be plugged in here, too
dojo.byId("content").innerHTML = data;
}
-
7/29/2019 Dojo Quickstart
20/32
}
});
};
dojo.addOnLoad(init);
XHR has limitations. The big one being thaturlis not cross-domain. You can't
submit the request outside of the current host (eg:
tourl:"http://google.com"). It is a known limitation and a common mistake
when getting excited about Ajax. Dojo provides alternatives
likedojo.io.iframeanddojo.io.scriptfor more advanced usage.
You also may experience problems with the Ajax samples if you are using
Internet Explorer without a web server (from the local filesystem). It is a knowsecurity limitation of XHR and IE. While most of these examples do work from
the filesystem, it is recommended you have a web server accessible to host
the Dojo source, and your tests.
A full list of XHR parameters is available at theAPI page, or inthe Dojo Book. We
are only going to skim the surface here.
Sending Data
All Dojo XHR methods are bi-directional. The only difference is the method.
Usingdojo.xhrPost, we use the POST method, embedding the data in the
request (as opposed to the query string as withdojo.xhrGet). The data can be
set directly as an object passed to thecontentparameter:
dojo.addOnLoad(function(){
dojo.xhrPost({
url:"submit.html",
content: {
"key":"value",
"foo":42,
"bar": {
http://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.__xhrArgshttp://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/ajax-transportshttp://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.__xhrArgshttp://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/ajax-transports -
7/29/2019 Dojo Quickstart
21/32
"baz":"value"
}
},
load:function(data,ioargs){
console.log(data);
}
});
});
Or more commonly, conveniently converted from aformparameter. First, make
a simple unobtrusive form in theskeleton.html:
Name:
Then, add in some JavaScript to submit the form by usingdojo.connectto listento theonSubmitevent, and post the contents of the form to an alternate URL:
// sumbit the form
var formSubmit =function(e){
// prevent the form from actually submitting
e.preventDefault();
// submit the form in the background
dojo.xhrPost({
url:"alternate-submit.php",
form:"mainForm",
-
7/29/2019 Dojo Quickstart
22/32
handleAs:"text",
handle:function(data,args){
if(typeof data =="error"){
console.warn("error!",args);
}else{
// show our response
console.log(data);
}
}
});
};
dojo.addOnLoad(function(){
var theForm = dojo.byId("mainForm");
// another dojo.connect syntax: call a function directly
dojo.connect(theForm,"onsubmit","formSubmit");
});
Noticee.preventDefault()being used again. The default nature of a form
being submitted to to visit a new page, and we want to prevent that from
happening.
An examplealternate-submit.phpwould look like:
-
7/29/2019 Dojo Quickstart
23/32
print "".$key." = ".$var."";
}
print "";
?>
Object Data
Getting text back from the server is nice, but the really great stuff comes when
you start passing JavaScript objects around. Using a
differenthandleAs:attribute, we can alter how Dojo handles the response data.
Make a new file namedsimple-object.jsonto load:
{
foo:"bar",
name:"SitePen",
aFunction:function(){
alert("internal function run");
},
nested: {
sub:"element",
another:"subelement"
}
}
We'll target our xhrPost url: to the new file, and supply ahandleAs:
"json"parameter to convert the response data to an actual object we can use:
var postData =function(){
dojo.xhrPost({
url:"js/simple-object.json",
-
7/29/2019 Dojo Quickstart
24/32
handleAs:"json",
load:function(data,ioargs){
// success: set heading, run function
dojo.byId("testHeading").innerHTML +=" by: "+data.name;
if(data.aFunction && data.aFunction()){
// we just ran data.aFunction(). should alert() ...
}
}
});
};
dojo.addOnLoad(postData);
A message will be thrown wanting you to use "json-comment-filtered" as a
handleAs: value. You can either use the alternate value, or set your
djConfig'susePlainJson: trueto deprecate this warning.
This allows us to send literallyanykind of data back and forth across the wire,
without ever interrupting the user experience.
Dijit: Prepackaged
Dojo's widget system is called Dijit. Dijits are the official, accessible, themed
components shipped with the Dojo Toolkit. It has its own namespace, and
likewise its own collection of utility functions:
dijit.byId("firstWidget"); // is a reference to the actualwidget.
dijit.byId("firstWidget").domNode; // is the domNode the widgetuses
// as opposed to:
-
7/29/2019 Dojo Quickstart
25/32
dojo.byId("testHeading"); // is a domNode in our page
Using dijits
There are two ways to makeDijits: via markup, or programatically. The markup
route breaks W3C validation because Dojo conveniently uses customized
attributes in the makrup to configure the widget. If this concerns you, it can all be
done with script. We'll do both.
Start by making a new skeleton file, including a couple changes for dijit styling:
the default theme tundra's CSS, and setting to enable
it.
Dijit Test Page
// our code, and dojo.requires()
-
7/29/2019 Dojo Quickstart
26/32
Dijit Skeleton Page
Dijit uses Dojo's package system to track dependancies via dojo.require.
Simply call in the modules you need in a tag. For instance, to use
a dijit.Dialog anddijit.form.Button, you need the following calls:
dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");
The dijit.Dialog is a modal dialog box. It takes the node's content, and displays
it front-and-center on the viewport, awaiting user interaction. It can also act as
a form element. To explore beyond this guide, visit the dijit.Dialog API Pages,
or the Book overview.
From markup
You can specify all the attributes needed to setup your widget directly in markup,
the most important being the dojoType. The parser finds the dojoType attribute,
and turns the node into a Dijit with the matching classname. title is a common
attrbute used by many widgets with headings.
http://api.dojotoolkit.org/jsdoc/dijit/1.2/dijit.Dialoghttp://api.dojotoolkit.org/jsdoc/dijit/1.2/dijit.Dialog -
7/29/2019 Dojo Quickstart
27/32
I am the Content inside the dialog.
And Button
IfparseOnLoad is true, the widgets will be created, then addOnLoad code will be
excuted. If you want to execute code before widgets are parsed,
set parseOnLoad:false, and put your code inside an addOnLoad function asbefore. Issuing the command dojo.parser.parse();will create the widgets
when you are ready.
IfparseOnLoad is true, the parser is loaded automatically. Otherwise, you
must issue adojo.require("dojo.parser"); call to include the required
functions. All dijits use the parser, so it is included automatically.
From JavaScript
The same results can be achieved using valid HTML and JavaScript. Our markup is
simple, valid HTML:
I am the Content inside the dialog.
Show Button
And our script is standard dojo code. We pass all the attributes as an object into
ourcontstructor, and tell it to use the node "sampleNode" for it's content. All
Dijits (or declared classes) can be created using the JavaScript new function.
-
7/29/2019 Dojo Quickstart
28/32
dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");
dojo.addOnLoad(function(){
// make the button
var theButton =new dijit.form.Button({
onClick:function(){
console.log("clicked");
}
},"myButton");
// make our Dialog
var theDijit =new dijit.Dialog({
title:"The First Widget"
},"sampleNode");
// make sure its started. parser does this if using markup
theDijit.startup();
});
When the button is clicked, you should see the word "clicked" in your Firebug (or
Firebug Lite) console.
Manipulating The Widget
With our dialog successfully loaded and parsed (no errors were thrown, and the
content of the Dialog is hidden), we need to explore some of the ways to
manipulate the widgets. The function dijit.byId gives us a reference to our
widget. The dijit.Dialog has an id ofsampleNode.
To make the button the button control the dialog, modify the
button's onClick attribute to do more than print text:
-
7/29/2019 Dojo Quickstart
29/32
I am the Content inside the dialog.
Show Dialog
If using the programmatic method, modify the lines that create the button:
// make the button
var theButton =new dijit.form.Button({
onClick:function(){
dijit.byId("sampleNode").show();
}
},"myButton");
The dijit.Dialog inherits from a dijit.layout.ContentPane which provides a
few content-handling methods, including setHref. Add a new button outside the
dialog with a new onClick function:
I am the Content inside the dialog.
Show Dialog
-
7/29/2019 Dojo Quickstart
30/32
Change Content
Or Programatically by adding another button to our HTML:
I am the Content inside the dialog.
Show Button
Change Dialog
And an additional new call:
// make the button
var theButton =new dijit.form.Button({
onClick:function(){
dijit.byId("sampleNode").show();
}
},"myButton");
var theButton =new dijit.form.Button({
onClick:function(){
dijit.byId("sampleNode").setHref("sample.txt");
}
-
7/29/2019 Dojo Quickstart
31/32
},"otherButton")
Adding an id attribute to the paragraph inside the Dialog is an easy way to
demonstrate another useful Dijit tool, dojo.getEnclosingWidget, to find which
widget contains a passed domNode:
// show the dialog onLoad, without knowing it's id
dojo.addOnLoad(function(){
// add
to the dialog content
var p = dojo.byId("myPara");
var theDijit = dijit.getEnclosingWidget(p);
theDijit.show();
});
Getting Help
In addition SitePen's various commercial support options, there are a number
of ways to find helpful information on your own. Dojo has a large community of
developers and hobbyists all across the globe that are willing to assist with
problems and offer guidance. Many tutorials and examples exist and are ready to
be found, you just have to look.
Here are some vital community resources available to assist you in your Dojo-
learning, and some hints to ensure success:
Dojo Search
Search first, ask later. A quick stop at the dojotoolkit.org search pageusually
turns up lots of commonly encountered problems. The new search engine has
options to help you target specific resources in the Dojo community, like blogs,
forums, or archived mailing lists.
Dojo Forums
If you are unable to find any discussion or book entry already, start a new topic in
the Dojo forums.
http://www.sitepen.com/services/http://search.dojotoolkit.org/http://search.dojotoolkit.org/http://www.dojotoolkit.org/forumhttp://www.sitepen.com/services/http://search.dojotoolkit.org/http://www.dojotoolkit.org/forum -
7/29/2019 Dojo Quickstart
32/32
It helps to provide examples contained within tags, and to politely state
your question. If you have tried other methods and failed, mention them as well.
The more infomation you provide in your post, the more likely someone is going
to quickly be able to assist you.
Also available on the Dojotoolkit website: a collection ofFequently AskedQuestions.
#dojo
Join the #dojo chat room on the irc server irc.freenode.net. This room acts as
a realtime development center for numbers of people ranging from beginner to
expert. Often, many core Dojo developers are available for any level of
discussion, at seemingly odd hours of the day. There is no experience
requirement, just a desire to learn.
The conversations range from deeply technical to outlandishly silly. It is a very
friendly room, and a great way to be in immediate contact with like minded
people while developing or learning Dojo. The first rule in the channel topic "Don't
Ask to Ask, just Ask." means just that: Jump right in, and start talking. If help is
available, you will likely get a response.
Mailing Lists
Though the forums have taken the place of the once-active mailing lists, thisresource is still available, and the preference of some. Simply signup, and begin
writing a thoughtful, well researched question, and you are typically going to
receive a response. The more thought you put into your post, the more willing
people will be to help you.
There are several thousand subscribers to dojo-interest, so civility is expected
of everyone.
It is important to remember the Dojo community is entirely voluntary. People
helping other people for the good of the Open Web, typically in their spare time.Civility is expected of everyone, and you are not guarenteed any speedy
response, if at all. If you find things within the community to be lacking, you are
always welcome to contribute. See the Getting Involved guide for more
information about what you can do. The community grows daily, and your
contributions are just as welcome as everybody else's.
http://dojotoolkit.org/support/faqhttp://dojotoolkit.org/support/faqhttp://dojotoolkit.org/mailman/listinfo/dojo-interesthttp://www.dojotoolkit.org/communityhttp://dojotoolkit.org/support/faqhttp://dojotoolkit.org/support/faqhttp://dojotoolkit.org/mailman/listinfo/dojo-interesthttp://www.dojotoolkit.org/community