Dojo: Hola Mundo

[Fuente: http://dojotoolkit.org/documentation/tutorials/1.6/hello_dojo/]

En este tuto cargaremos DOJO en una pagina HTML simple, poniendo algunas de las funciones básicas de DOJO a funcionar. Tocaremos la estructura modular de DOJO y discutiremos como cargar dependencias para tener un experiencia de usuario más rica.

  • Dificultad: principiante
  • Dojo Version: 1.6

Introducción

Nuestro punto de comienzo es una pagina HTML simple. Queremos cargar DOJO en esa pagina y añadir algun codigo que muestre que está bien cargado.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial: Hello Dojo!</title>
<!-- load Dojo -->
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js"></script>
</head>
<body>
<h1 id="greeting">Hello</h1>
</body>
</html>

View Demo

Vemos como hemos enganchado la libreria dojo.js via CDN. Ahora necesitamos algón código para que Dojo este preparado para funcionar y podamos hacer algo con él.

dojo.ready

Si jquery tiene el document.ready , pues Dojo tiene el dojo.ready. Es decir es el método para saber cuando el DOM del HTML  se ha cargado y todas las librerias (incluida Dojo) han sido cargadas. Al dojo.ready le pasamos una función y la función se ejecutará cuando llegue el momento ready:

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial: Hello Dojo!</title>
<!-- load Dojo -->
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js"></script>
<script>
dojo.ready(function(){
alert("Dojo version " + dojo.version + " is loaded");
});
</script>
</head>
<body>
<h1 id="greeting">Hello</h1>
</body>
</html>

 

View Demo

En vez del alert utilicemos una función de Dojo para ir cogiendo el gustillo.

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial: Hello Dojo!</title>
<!-- load Dojo -->
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js"></script>
<script>
dojo.ready(function(){
dojo.byId("greeting").innerHTML += ", from " + dojo.version;
});
</script>
</head>
<body>
<h1 id="greeting">Hello</h1>
</body>
</html>

 

View Demo

Si tenemos más de una linea  en el dojo.ready es común utilizar una función init:

 

function init() {
alert("Dojo ready, version:" + dojo.version);
// More initialization here
}
dojo.ready(init);

 

NOTA: observar que al dojo.ready le pasamos el objeto función en si , sin comillas.

Módulos

Dojo es un toolkit modular, con un sistema de paquetes que te prmite cargar solo el código que necesites dentro de tu página y hacer que la gestión de dependencias sea más fácil. Para ello Dojo introduce el dojo.require para indicar la dependencia del módulo indicado.

De momento, apuntemos que cuando cargamos dojo.js, no estamos cargando el Dojo Toolkit entero, sólo los módulos básicos tales como el sistema de paquetes , el sistema de eventos, Ajax, DOM helpers y otras funcionalidades comunmente utilizadas.

Carga de módulos

Los básico de Dojo incluye un framework de animación para efectos visuales y un par de los efectos más comunes (el dojo.fadeOut y el dojo.fadeIn). Eso esta bien, pero nosotro queremos algo que haga que el saludo de nuestra pagina de ejemplo se deslice por la  pantalla. Para eso utilizaremos dojo.fx.slideTo. El módulo dojo.fx no está incluido en el dojo.js asi que necesitaremos cargarlo:

 

// New: Require in the dojo.fx module
dojo.require("dojo.fx");
// Remember, dojo.ready waits for both the DOM and all dependencies
dojo.ready(function(){
// The piece we had before - change our innerHTML
dojo.byId("greeting").innerHTML += ", from " + dojo.version;
// Now, slide the greeting
dojo.fx.slideTo({
top: 100,
left: 200,
node: dojo.byId("greeting")
}).play();
});

 

The slideTo effect we want is a part of the dojo.fx module. The dojo.require line states the dependency, and asks the loader to load the file if it is not already available. There’s no new script tag to fiddle with, and crucially, the rest of our initialization needn’t change — we still use dojo.readyand our code will only run once the DOM is ready and all dependencies are loaded.

The next part is to put what we loaded to use. Like all property animations in Dojo, we pass in an object with a node reference, and any other properties to configure the animation. We’ll be looking closer at animations in Dojo in a future tutorial.

View Demo

Conclusion

Getting started with the Dojo Toolkit is as simple as adding a script tag, but the broad scope of the toolkit is placed at your fingertips, as and when you need it. In this tutorial we’ve taken the first step towards putting Dojo to work in your web sites and applications. In future tutorials in this series we’ll visit each of the major groups of functionality — from DOM helpers to Ajax, effects, events and more — exploring and explaining each step of the way.