Tuesday 27 November 2012

Dojo JavaScript Example

Get Started With Dojo

It’s becoming a desktop web. Reactive interfaces are blurring the lines between desktop applications and web applications, which in consequence, makes the web more powerful. It’s all built on JavaScript — a language known for making coding a chore.
The Dojo Toolkit helps you create these richer interfaces with its widgets, called Dijits. These user interface elements, from buttons to pop-up boxes, are easy to use and sometimes don’t even require JavaScript.
In this tutorial, we’ll look at how Dijits work and how Dojo can help you write some powerful web applications.

What you’ll need

  • HTML and CSS experience
  • A little JavaScript experience

How Dojo is Different

If you’re expecting yet another JavaScript framework, Dojo will surprise you. Where libraries like jQuery and Prototype focus on accessing the Document Object Model (DOM), Dojo creates a rich layer on top of the DOM.
In its core library, Dojo has some functions you would expect. The real power, and where this tutorial focuses, is creating rich interfaces. As it turns out, Dojo does this with often very little JavaScript.
Dojo also loads only the files it needs, when it needs them. So, if you only need the button widget, that’s all the JavaScript you’ll need to load. All this is done for you from a single Dojo file reference.
In the sections below, I’ll show how to add a couple widgets to your website using mostly markup. Then, for the JavaScript coders, I’ll show how Dojo still lets you use your programming skills to increase the mojo of Dojo.
Let’s get started.
Woohoo! You clicked and now you see this box.


Preparing the Dojo

Now that you know what’s up with Dojo, let’s use some of it. Before we can get down and dirty with it, we need to set the stage. Copy the following text to a new file.
01<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02
03<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
04
05<head>
06
07    <script type="text/javascript" src="http://o.aolcdn.com/dojo/1.2.0/dojo/dojo.xd.js" djConfig="parseOnLoad: true"></script>
08
09    <script type="text/javascript">
10
11        // JavaScript and Dojo calls will go here
12
13
14
15    </script>
16
17
18
19    <style type="text/css">
20
22
23    </style>
24
25</head>
26
27<body class="tundra">
28
29<!-- HTML and Dojo tags will go here-->
30
31
32
33</body>
34
35</html>
Alternatively, copies of the code are hosted on the Dojo template Webmonkey code library or right click on this link and select Save Link As instead.
Chances are pretty good that the code looks familiar to you. It’s straight-forward HTML, but with three little hooks for Dojo’s JavaScript and CSS.

The Dojo JavaScript

As with any JavaScript framework or library, the first thing we have to do is include the code file. But, wait, we haven’t downloaded anything to include, right? Good observation!
With Dojo, you can load a single file from the AOL Content Delivery Network (CDN), and don’t have to host the file yourself. The file will be delivered fast, it will be appropriately cached and you don’t have to mess with downloading and unpacking the code. Cool!
1<script type="text/javascript" src="http://o.aolcdn.com/dojo/1.2.0/dojo/dojo.xd.js" djConfig="parseOnLoad: true"></script>
2
3<script type="text/javascript">
4
5    // JavaScript and Dojo calls will go here
6
7
8
9</script>
The first line calls to the Dojo JavaScript and also prepares a message for Dojo. It says that we want Dojo to parse the page as soon as the page loads. That way, it can find the other pieces of Dojo code. We’ll write the other pieces—and the stuff within the second set of script tags—in later sections.
If you prefer to host the Dojo JavaScript files yourself, you can download the latest version. This tutorial will continue to use the hosted Dojo for its many conveniences, including letting you run each example as a single HTML file on your own computer.

The Dojo CSS

Since the big deal about Dojo is its stylized widgets (or Didjits), how things look is an important part of Dojo’s appeal. Design is controlled via CSS themes. You can create and alter your own themes, but the default one is called Tundra and can also be loaded from the AOL CDN:
1<style type="text/css">
2
4
5</style>
Like the JavaScript, you can host the file yourself if you want. Tundra, and two other themes, come packaged with the Dojo download.

The Dojo Class Name

At this point we have loaded the JavaScript and the CSS, but the widgets won’t look right without this next simple line:
1<body class="tundra">
Here I’ve given the class “tundra” to the HTML <body> tag. If you take a look at the CSS theme, you’ll see that just about every line begins with .tundra, so having everything within an element with class="tundra" is important.
At this point, we’ve done enough stage-setting. It’s time to start the Dojo-writing. In the next section, we’ll start out nice and slow by changing the way a simple button looks.

Create a Simple Button

For this first example, you’ll be styling an ordinary button. The Tundra CSS theme takes care of how it looks. Dijits, the widget-making part of the Dojo Toolkit, is used to transform the regular button into a special button.
You can the entire HTML file or follow along below to write or copy the important sections piece by piece.
The first thing you need to do is make sure the code that produces the button is loaded. The link to the Dojo JavaScript file we included earlier takes care of this for you, but since Dojo only gives you what you need, you need to tell it what you want.
Place this line inside the empty script tags in your file:
1dojo.require("dijit.form.Button");
Now Dojo is ready to create button, but we need to show it where. That happens in our HTML. Place this markup where you would like the button to appear:
01<button dojoType="dijit.form.Button" id="buttonTest">
02
03    Clicky
04
05    <script type="dojo/method" event="onClick">
06
07        alert('Clicky-click! You clicked and now you see this box');
08
09    </script>
10
11</button>
Save and reload your file in a browser. You should see a normal button for a moment, then a square button with a slight gradient. Something like this:


At a glance, the code looks like normal HTML, but you might have noticed some strange attributes and embedded JavaScript. Let’s look a little closer.
The <button> tag contains a dojoType attribute. This tells Dojo how we want to transform this object. We want to make it a button. Or, as Dojo calls it, a dijit.form.Button (remember that from the JavaScript?).
The non-tag content within the button makes up the text of the button. In this case, “Clicky.”
Finally, we have another script block. Its a special one, though, because it is of type dojo/method and declares the onClick event. We can put any JavaScript code within this block, but since it’s nested inside the button, it’s best to keep it short. If you need more than one or two lines, use a function. We’ll show you how in the final example.
In this case, we’ll just toss an alert function in there to make sure everything is working.
You’ve probably already clicked on the button by now. If for some reason you’ve held off, go for it. A default JavaScript alert box pops up annoyingly. That’s how you know it’s working!
Are you wondering if that box could be less annoying and look a little nicer? I was, too. And Dojo has an answer for you in the next section.

A Better Alert Box

I cringe whenever I see the alert function used on production websites. Even Google does it. And yet, when it comes down to examples, I still find myself often using the normal JavaScript alert function. It’s such a handy way to prove something’s happening.
Dojo has a much better alert box, called Dialog. In this section, we’ll trigger this new alert box with the same button we used on the previous section.
As with the previous sections, the impatient can download the entire HTML file here. To learn what each piece of code does, read on.
In the script section at the top of the page, add this line below the dijit.form.Button line:
1dojo.require("dijit.Dialog");
This tells Dojo that we’re going to be using the Dialog widget.
Now you can remove that alert line from the dojo/method script tag. Don’t you feel better already? Where you used to have the alert line, replace it with this line:
1dijit.byId('dialogTest').show();
Here we tell Dojo (via dijit) to grab an object with the id dialogTest and then display it with the show() function. This object does not exist yet. So, let’s create it.
This is the object that will become our Dialog. Paste this special <div> tag below your button (but before the ending body tag).
1<div dojoType="dijit.Dialog" id="dialogTest" title="Clicky-click!">Woohoo! You clicked and now you see this box.</div>
The dojoType may look familiar from the button code, which used a similar syntax. In this case, the type is dijit.Dialog. We also gave the div an id, dialogTest, which is the same as what we passed to dijit.byId above. Awesome! This stuff is starting to come together.
Have you saved the file and reloaded yet? Click the button and you’ll see a better alert box:

This is much better than the alert function in several ways. First, we have control over the text in the title bar of the box. Secondly, it doesn’t make an annoying beep that makes the user think something is wrong. Lastly, it looks a lot nicer because it blends in with other interface elements, thanks to Dojo theming.
Despite all these improvements, this alert box could get better. I’ll show you how in the next section.

Make Your Alert Box Programmatically

At this point, you’ve seen how Dojo can change the way interface elements look. If you’ve done much JavaScript programming in the past, one thing might have bothered you a little: we haven’t done much actual JavaScript programming.
The Dojo Button and Dialog were both created completely with HTML-like code, relying on Dojo itself to do the parsing. To have a truly useful alert box function, we don’t want to toss in a special div every time we want to display a message. For this, we need a programmatically-involved alert box!
Here’s the code now or read on for constructing it yourself.
Much of our code from the previous section will remain the same. Inside the script tags at the top of the code, we need to add a new function that I’ve written. I’m calling it dialogAlert:
01function dialogAlert(txtTitle, txtContent)
02
03{
04
05    var thisdialog = new dijit.Dialog({ title: txtTitle, content: txtContent });
06
07    dojo.body().appendChild(thisdialog.domNode);
08
09    thisdialog.startup();
10
11    thisdialog.show();
12
13}
We can call this new function as often as we like, much as we used to call the alert function. Instead of a single message, this alert box also uses a title.
The function, as you see, contains four lines. In the first, we create a new Dialog object with the title and content. It seems like we’re done, right? Not yet; we need to add it to the page (the second line), call the startup function (third line—more on this in a moment) and finally show the Dialog.
Why do we have to both call startup and show it? The functions do two totally different things. In startup, Dojo prepares the object for display, but also makes sure that it’s currently hidden. After startup is called, we’re exactly to the point that we were in the previous section before the button is clicked. Once /show is called (and we called that same function in the old Dialog code), the box is displayed for the user.
Now we have to call this new function. Replace the code inside the onclick event with this line:
1dialogAlert('Clicky-click!', 'Woohoo! You clicked and now you see this box.');
Save and reload. When you click the button, you should see the same dialog you saw in the previous section. Now it’s been created with JavaScript, without the need to add a special div to the markup.

The best part is that if you want to call it again, you can. You can also use different content for each time.
Copies of this code are hosted on the Webmonkey code library or right click on this link and select Save Link As instead.

Where to go From Here

This tutorial has given just a taste of what Dojo can do. You’ve restyled a button and created a better alert box in two ways. There are many other widgets, including sliders, date selection objects and even a full rich text editor.
The obvious place to go from here is to start incorporating these widgets into your user interfaces. The official Dojo documentation is a bit lacking for beginners, though the online Dojo book can be helpful. If you’re looking to create more widgets, there are some great examples at DojoCampus, including code.
If you need a little inspiration, check out Sites and AOL, which each make a healthy use of Dojo. Then, try it yourself, and let Webmonkey know what you make.

No comments:

Post a Comment

Do you think it could be useful for you? Share your thoughts with us!