complete dojo

106
Dojo Tutorial 1 5/19/2012 Girish Srivastava [email protected]

Upload: girish-srivastava

Post on 09-May-2015

8.651 views

Category:

Technology


0 download

DESCRIPTION

Complete Dojo for Beginers...

TRANSCRIPT

Page 1: Complete Dojo

Dojo Tutorial

1 5/19/2012

Girish Srivastava [email protected]

Page 2: Complete Dojo

Objective In this tutorial, we will learn everything about the dojo. After

completing the tutorial you will be able to understand about Dojo

framework.

This Dojo tutorial covers:

2 5/19/2012

Page 3: Complete Dojo

Introduction to Dojo

What is Dojo? Dojo is JavaScript framework released as open source

software. This JavaScript toolkit provides many components to develop rich internet applications.

You can use Dojo toolkit to develop dynamic web applications. Dojo toolkit will put life in your web application and turn it into highly interactive application. You can turn your web application into desktop like web application.

Dojo offers many widgets, utilities and ajax libraries to develop your application.

Dojo is released under BSD or AFL license

Dojo is free and can be used to develop free or commercial application.

3 5/19/2012

Page 4: Complete Dojo

4 5/19/2012

Page 5: Complete Dojo

Features of Dojo Dojo is based on HTML and JavaScript, so its easy for the developers to learn it

fast.

There is no requirement of learning new programming language. Just HTML and JavaScript knowledge if sufficient.

Dojo provides higher abstraction layer to the programmer. So, it helps the programmers to develop powerful functions very easily.

Dojo has already invented the wheels for the programmers and now programmers just have to use the Dojo api into their application

Here is the list of components that comes along with Dojo framework:

DOJO Tree

DOJO Button

DOJO Calendar control

DOJO Grid

DOJO List box

and many more..

5 5/19/2012

Page 6: Complete Dojo

6 5/19/2012

Page 7: Complete Dojo

7 5/19/2012

Page 8: Complete Dojo

8 5/19/2012

Page 9: Complete Dojo

DOJO Core

9 5/19/2012

Page 10: Complete Dojo

What Is Dijit?

10 5/19/2012

Page 11: Complete Dojo

11 5/19/2012

Page 12: Complete Dojo

12 5/19/2012

Page 13: Complete Dojo

13

What is a widget

A widget is an object, that contains not just logic, but also a

way to be presented on the screen

The way a widget is presented is the widget’s template

Widget can contain other widgets

5/19/2012

Page 14: Complete Dojo

14

General widgets General purpose widgets that are used to make a web page

more “application-like”

Menu

Dialogs

Inline editing

Toolbar

ProgressBar

Tree – that can be connected to data source

Rich text editor – with plugins architecture to configure the editor’s functions

There are many more general widgets in dojoX

5/19/2012

Page 15: Complete Dojo

15

What makes a widget

A widget is composed of two resources

A .js file that contains the logic of the widget

An html snippet that contains the way the widget is presented

This resource is called the widget’s template

The html code itself can be in another file or inlined in the .js file

This allows later on to perform runtime optimizations, by placing the

template in a separate file during development time, and inline it as part

of the build process

5/19/2012

Page 16: Complete Dojo

Benefits of Dojo Framework

Dojo toolkit provides many widgets to develop the UI for web

applications.

Dojo is one of the robust ajax framework that can be used to develop

enterprise grade application.

Following are the benefits of Dojo.

Associative arrays

Loosely typed variables

Regular expressions

Objects and classes

Highly evolved date, math, and string libraries

W3C DOM support in the Dojo

16 5/19/2012

Page 17: Complete Dojo

Disadvantages of Dojo

Developer depends on the browser support for the Dojo

There is no way to hide the Dojo code in case of commercial

application

17 5/19/2012

Page 18: Complete Dojo

JQuery versus Dojo versus YUI

•JQuery Pros:

- JQuery is the most popular one of them all.

- It is very easy to use and to understand.

- The core library is only 15Kb in size.

- Their statement is: ‘The Write Less, Do More, Javascript

Library’.

Cons:

- Hard to use with object oriented programming

- JQuery is a library

18 5/19/2012

Page 19: Complete Dojo

•YUI(The Yahoo! User Interface Library)

Pros:

- It is developed by Yahoo

- Fully documented, with a great API browser

- Very consistent and reliable

- Also contains unit testing framework

- YUI is a framework

Cons:

- Heavy page weight

- Very few utility or helper functions/methods

- Lacks the use of chaining methods together

19 5/19/2012

Page 20: Complete Dojo

• Dojo Toolkit Pros:

- Debug your code in Firebug

- Dojo integrated in Zend Framework

- Hierarchical package system speeds loading

- Dojo is a framework

Cons:

- Dojo fails in online documentation

When we compare these 3 libraries/frameworks, I found the

following which was quite useful.

http://selectors.turnwheel.com/slickspeed.php

20 5/19/2012

Page 21: Complete Dojo

Based on these results, we can conclude that YUI is the slowest one. This is also the reason why we didn’t chose for YUI. Dojo and JQuery scores the best.

Knowing that JQuery is the easiest to use and immense popular, Dojo has its advantage of being integrated in Zend Framework. Also, the difference in being a library or framework counts. - A library is about reusable functionalities, but a framework is about reusable behaviours - A library is something you call/inherit from your code, but framework is something that calls your code or provide services for your code - A library is a collection of components and classes, where framework is how abstract classes and components interact with each others

Dojo is a framework and JQuery a library.

JQuery is good for small websites where you want to achieve a ‘WOW’ factor in relative short time.

But when you are building an application, you need a robust framework where you can integrate your own codes.

21 5/19/2012

Page 22: Complete Dojo

22 5/19/2012

Page 23: Complete Dojo

23 5/19/2012

Page 24: Complete Dojo

24 5/19/2012

Page 25: Complete Dojo

25 5/19/2012

Page 26: Complete Dojo

Loading Dojo ToolKit…

26 5/19/2012

Page 27: Complete Dojo

27 5/19/2012

Page 28: Complete Dojo

Install Dojo

Downloading Dojo

You can download the latest version of Dojo from its official

site http://dojotoolkit.org/.

Download the Dojo toolkit directly

from http://dojotoolkit.org/download.

28 5/19/2012

Page 29: Complete Dojo

29 5/19/2012

Page 30: Complete Dojo

30 5/19/2012

Page 31: Complete Dojo

Themes and Theming

5/19/2012 31

Dijit Themes lend a consistent look and feel to widgets.

Themes are collections of images (icons and background images) and

CSS files that bring a common visual style (font, color, texture,

layout, animation, etc.) to all the widgets.

Using a Theme To include a given theme on your page or application, first include

the themeName.css file (one of claro.css, tundra.css, nihilo.css, or soria.css):

<link rel="stylesheet" href="dojo/dijit/themes/claro/claro.css" />

Then, add a theme class name to the parent <body> element, like:

<body class="claro">

It is recommended you include the theme CSS file before dojo.js to avoid any

potential race conditions where widgets start rendering before the theme has

finished loading. Thus, putting it all together:

Page 32: Complete Dojo

Example

5/19/2012 32

<html>

<head>

<title>Hello, Dijit</title>

<link rel="stylesheet" href=“dojocore/dijit/themes/claro/claro.css">

<script src="lib/dojo/dojo.js"></script>

<script type="text/javascript">

dojo.require("dijit.Dialog");

</script>

</head>

<body class="claro">

<h1>Hello, Dijit</h1>

</body>

</html> http://dojotoolkit.org/reference-guide/1.7/dijit/themes.html

Page 33: Complete Dojo

Dojo Hello World

33

<html>

<head>

<title>Hello World</title>

<script type="text/JavaScript" src=“dojoroot/dojo/dojo.js"

djConfig="parseOnLoad: true"> </script>

<style type="text/css">

@import "dojoroot/dijit/themes/tundra/tundra.css";

@import "dojoroot/dojo/resources/dojo.css";

</style>

<script type="text/JavaScript">

dojo.require("dijit.form.Button");

</script>

</head>

<body class="tundra">

<button dojoType="dijit.form.Button" id="helloButton"> Hello World

<script type="dojo/method" event="onClick">

alert("Hello Dojo.");

</script>

</button>

</body>

</html> 5/19/2012

Page 34: Complete Dojo

The dojo.js file is the main component in the Dojo toolkit. You can

use Dojo by including this file in your page.

The djConfig attribute is used for configuring the Dojo runtime.

We want to use Dijit's button widget, so you must include the Dijit

style sheet, as shown here: <style type="text/css">

@import "dojoroot/dijit/themes/tundra/tundra.css"; </style>

Dijit allows you to choose a theme to use. The default theme is tundra,

which we use in our sample code by including tundra.css.

34 5/19/2012

Page 35: Complete Dojo

Dojo uses the concept of modules, which are similar to Java packages.

Before you use functionality from a particular package, you must

include that package in your page. The dojo.require() call -- similar

to Java's import statement -- is used for importing a Dojo module: o <script type="text/JavaScript">

o dojo.require("dijit.form.Button");

o </script>

The line dojo.require("dijit.form.Button") tells Dojo to load

the dijit.form.Button class on your page.

To use any widget in a page, you must import its code using

dojo.require().

35 5/19/2012

Page 36: Complete Dojo

You can use a Dijit widget by using the same markup as that of the

normal HTML element. The only difference is that you must add

the dojoType attribute indicating name of the Dijit widget that you

want to use: <button dojoType="dijit.form.Button" id="helloButton">

Hello World

<script type="dojo/method" event="onClick">

alert("Hello Dojo.");

</script> </button>

Like This we can create can create different different examples.

CheckBox …

ComboBox…

RadioButton… etc.

36 5/19/2012

Page 37: Complete Dojo

Configuring the Dojo runtime

37

Dojo allows you to configure the runtime using the djConfig object.

The default value of parseOnLoad is false. If you do not set it to true, by default, system will not create any widgets.

Dojo creates the djConfig object when the framework initializes -- that is, when Dojo.js loads.

If you want to make any changes in djConfig, you should do so before dojo.js is loaded.

Any changes that you make in djConfig are ignored after dojo.js is loaded.

Here, we set the parseOnLoad property to true. This causes Dojo to

attach an onload event handler for the body. From that event handler, Dojo traverses the DOM tree and instantiates the widgets whenever a widget markup is located.

5/19/2012

Page 38: Complete Dojo

38

The easiest and most commonly used approach is to add the

djConfig attribute to the <script> element that refers to

dojo.js:

<script type="text/JavaScript"

src=“dojocore/dojo/dojo.js"

djConfig="parseOnLoad: true, isDebug: true“>

</script>

isDebug: This flag turns debugging on or off.

Its default value is false. When you turn this flag on, Firefox

generates extended debugging information in Firebug.

If you're using some other browser, it includes the Firebug

Lite script files in the page and starts displaying the Firebug

Lite console. 5/19/2012

Page 39: Complete Dojo

•Event Handling

•Add Buttons

Add a new dojo.require() statement to include the code for the

dijit.form.Button widget.

<script type="text/javascript">

dojo.require("dijit.form.Button");

</script>

Just above the line:

</body>

Add:

<br />

<button dojoType="dijit.form.Button">OK</button>

<button dojoType="dijit.form.Button">Cancel</button>

5/19/2012 39

Page 40: Complete Dojo

Understanding Dojo's Event Handling

Event handling works somewhat differently in Dojo than regular

DOM. First, let's recap DOM's event handling scheme.

For a regular button element, you will register an onclick event

handler as follows: <button onclick="showEventStd(this, event);">OK</button>

The "this" and "event" keywords tell the browser to supply the

element and the event object as parameters to the handler function.

The handler function looks something like this: function showEventStd(theElement, theEvent) {

alert("Event " + theEvent.type + " for element " + theElement.nodeName);

}

5/19/2012 40

Page 41: Complete Dojo

Cont… In Dojo, there are two main differences.

1. A Dojo button's onclick attribute takes the name of the event

handler method. You don't actually call the method like you do for a

regular DOM button.

2. Second, the event handler method gets only one parameter –

the Event object.

Let's have a look at an example. The event handler is registered as

follows: <button dojoType="dijit.form.Button" onclick="showEvent">OK</button>

The event handler method looks like this:

function showEvent(theEvent) {

alert("Event " + theEvent.type);

}

5/19/2012 41

Page 42: Complete Dojo

42

Continue with…

5/19/2012

Page 43: Complete Dojo

43 5/19/2012

Page 44: Complete Dojo

JavaScript Object Oriented Feature

5/19/2012 44

<html> <head> <Script language="JavaScript"> function MyClass() { this.myData = 10; this.myString = "my frist program"; } var myClassObj1 = new MyClass(); var myClassObj2 = new MyClass(); myClassObj1.myData = 20; myClassObj1.myString = "Obj1: my second program"; myClassObj2.myData = 30; myClassObj2.myString = "Obj2: last program"; alert( myClassObj1.myData ); alert( myClassObj1.myString ); alert( myClassObj2.myData ); alert( myClassObj2.myString ); </script> </head> </body> </html>

Page 45: Complete Dojo

Object-Oriented Programming

5/19/2012 45

The Object Oriented programming is a computer programming

paradigm.

Object Oriented programming is that computer program may be

seen as comprising a collection of individual units and objects, that is

on each other, as opposed to a traditional view in which a program

may be seen as a collection of functions or procedures, or simply as a

list of instructions to the computer.

Each object is capable of receiving messages, processing data, and

sending messages to other objects.

Page 46: Complete Dojo

5/19/2012 46

Object: The Object an instance of a class and object is the run-time manifestation of a

particular exemplar of a class.

Each object has own data, though the code within a class a subclass or an

object may be shared for economy.

Encapsulation

The Object-Oriented program using the myclass as defined permits accessibility of

its internal data representation as well as this methods and variable names global in

scope increasing the risk of name collisions.

The Object-Oriented program Encapsulation supports data hiding and the concept

of viewing objects as self-contained entities providing services to consumers.

Encapsulation is a modern programming languages of the principle of information

hiding itself in a number of ways, including encapsulation and polymorphism.

Page 47: Complete Dojo

Prototype-based OOP

5/19/2012 47

JavaScript implements a type of object-oriented programming

different to that used in Java™ code.

Whereas Java programming is based on a class-based OOP model,

JavaScript is based on a class-less-based OOP model commonly

known asprototype-based object-orientation.

Rather than defining a set of class templates from which objects are

created, objects are simply declared when needed.

When anobject needs to inherit features from another object, it can

simply clone the features of a prototype object.

One of the key advantages of prototypal OOP is that an object

prototype can be modified at run time, meaning that the definition of

the structure of objects is not strict.

Page 48: Complete Dojo

A basic object prototype in JavaScript

5/19/2012 48

function Car() { }

var myCar = new Car();

console.log(myCar);

This should produce the following output in the console log:

Object {}.

Defining a member variable in your object

function Car() { }

Car.prototype.current_speed = 0;

var myCar = new Car();

console.log(myCar);

This time, the console log will output something a bit more

interesting: Object{ current_speed=0 }.

Page 49: Complete Dojo

Adding a method to the prototype

5/19/2012 49

function Car() { }

Car.prototype.current_speed = 0;

Car.prototype.accelerate = function(increment)

{

this.current_speed += increment;

}

var myCar = new Car();

myCar.accelerate(30);

myCar.accelerate(20);

console.log(myCar);

The console output should produce the following: Object {

current_speed=50 }.

Page 50: Complete Dojo

Example

5/19/2012 50

<html> <head> <Script language="JavaScript"> function MyClass() { var m_data = 15; var m_text = "indian"; this.SetData = SetData; this.SetText = SetText; this.ShowData = DisplayData; this.ShowText = DisplayText; function DisplayData() { alert( m_data ); } function DisplayText() { alert( m_text ); return; } function SetData( myVal ) { m_data = myVal; }

Page 51: Complete Dojo

Example Cont…

5/19/2012 51

function SetText( myText )

{

m_text = myText;

}

}

var Obj1 = new MyClass();

var Obj2 = new MyClass();

Obj1.SetData( 30 );

Obj1.SetText( "Obj1: my cuntry" );

Obj2.SetData( 60 );

Obj2.SetText( "Obj2: my first javaScript progarm" );

Obj1.ShowData();

Obj1.ShowText();

Obj2.ShowData();

Obj2.ShowText();

</script>

</head>

</body>

</html>

Page 52: Complete Dojo

Functions

functions are objects

they have properties

they have methods

can be copied, deleted, augmented...

special feature: invokable

5/19/2012 52

Page 53: Complete Dojo

Functions

function boo(what) {

return what;

}

or

var boo = function(what) {

return what;

};

5/19/2012 53

Page 54: Complete Dojo

Functions

function boo(what) {

return what;

}

or

var boo = function bootoo(what) {

return what;

};

5/19/2012 54

Page 55: Complete Dojo

Return value

all functions return a value

if they don't explicitly, they return undefined

implicitly

functions can return other functions

5/19/2012 55

Page 56: Complete Dojo

Constructors

when invoked with new, functions return an object known

as this

you have a chance of modifying this before it's returned

you can also return some other object

5/19/2012 56

Page 57: Complete Dojo

Constructor functions

var Person = function(name) {

this.name = name;

this.speaks = 'fr';

this.say = function() {

return "Je m'appelle " +

this.name;

};

};

5/19/2012 57

Page 58: Complete Dojo

An object created with constructor

>>>

var julien = new Person("Julien");

>>>

julien.say();

"Je m'appelle Julien"

5/19/2012 58

Page 59: Complete Dojo

prototype

a property of the function objects

>>> var boo = function(){};

>>> typeof boo.prototype

"object"

5/19/2012 59

Page 60: Complete Dojo

Prototypes can be augmented

>>> boo.prototype.a = 1;

>>> boo.prototype.sayAh =

function(){};

5/19/2012 60

Page 61: Complete Dojo

Prototypes can be overwritten

>>> boo.prototype = {a: 1, b: 2};

5/19/2012 61

Page 62: Complete Dojo

How is the prototype used?

when a function is invoked as a constructor

var Person = function(name) {

this.name = name;

};

Person.prototype.say = function() {

return this.name;

}

5/19/2012 62

Page 63: Complete Dojo

How is the prototype used?

>>> var dude = new Person('dude');

>>> dude.name;

"dude"

>>> dude.say();

"dude"

5/19/2012 63

Page 64: Complete Dojo

Own properties vs. prototype’s

>>> dude.hasOwnProperty('name');

true

>>> dude.hasOwnProperty('say');

false

5/19/2012 64

Page 65: Complete Dojo

The prototype chain

5/19/2012 65

Page 66: Complete Dojo

It’s alive!

>>> typeof dude.numlegs

"undefined"

>>> Person.prototype.numlegs = 2;

>>> dude.numlegs

2

5/19/2012 66

Page 67: Complete Dojo

Inheritance

5/19/2012 67

Page 68: Complete Dojo

Inheritance via the prototype >>> var Dad = function()

{

this.family = “Rahul";

};

>>> var Kid = function(){};

>>> Kid.prototype = new Dad();

>>> var billy = new Kid();

>>> billy.family

“Rahul"

5/19/2012 68

Page 69: Complete Dojo

Inherit one more time

>>> var GrandKid = function(){};

>>> GrandKid.prototype = billy;

>>> var jill = new GrandKid();

>>> jill.family

“Rahul"

5/19/2012 69

Page 70: Complete Dojo

Inheritance… >>> jill.hasOwnProperty('family')

false

>>> jill.__proto__.hasOwnProperty('family')

false

>>> jill.__proto__.__proto__.hasOwnProperty('family')

true

5/19/2012 70

Page 71: Complete Dojo

Object-orientation in Dojo

One of the lesser-known facts about JavaScript is that it is an object-

oriented language.

However, it is a prototype-based object-oriented language that

doesn't have the same structure as class-based languages such as Java.

Dojo provides functionality to simulate class-based object-oriented

concepts such as declaring classes, constructors, and inheritance.

In the background, it takes care of things like prototyping,

inheritance, and various procedures that JavaScript requires.

5/19/2012 71

Page 72: Complete Dojo

Working with classes

Dojo provides a dojo.declare() method that you should

use to declare a new class. It accepts the following

arguments:

A string representing the name of the class that you want to

declare.

The name of the superclass or array of names of the

superclasses that you want this class to inherit from. (I'll talk

more about multiple inheritance later.)

A hashmap of properties for the class. The properties

represent both instance variables and member function of

this class.

5/19/2012 72

Page 73: Complete Dojo

Cont…

5/19/2012 73

Declaring a class

• dojo.declare("custom.javaworld.Worker",null,{

firstName: "",

lastName: "",

work: function(){

console.log("Working");

}

});

var johnDoe = new custom.javaworld.Worker();

johnDoe.work();

johnDoe.lastName ="Doe";

console.log("Last Name " + johnDoePerson.lastName);

Page 74: Complete Dojo

Cont…

Here the dojo.declare() method's first argument is

custom.javaworld.Worker -- the name of the class we want to

declare. The method's second argument is null because we don't want

to inherit this class from any other class. The third argument is a

hashmap, in which work is the property's name and its value is a

function. We thereby define a work() member function for

the Worker class.

Once the custom.javaworld.Worker class is declared, you can

create a new object instance of it by calling new

custom.javaworld.Worker().

Then you can start calling the new object's methods or assign values

to its member variables.

5/19/2012 74

Page 75: Complete Dojo

Constructors A constructor allows you to initialize every object of a class by executing

code whenever a new instance of the class is created.

Adding a constructor • dojo.declare("custom.javaworld.Worker",null,{

firstName: "",

lastName: "",

constructor: function(fName, lName){ console.debug("Constructor of com.javaworld.Worker called"); this.firstName = fName; this.lastName = lName;

},

work: function(){

console.log("Working");

}

});

var johnDoe = new com.javaworld.Worker("John","Doe"); console.log("First Name " + johnDoe.firstName); console.log("Last Name " + johnDoe.lastName);

5/19/2012 75

Page 76: Complete Dojo

Inheritance

The ability to extend other classes is one of the basic features of

object-oriented programming.

Dojo handles all the requirements for setting up an inheritance

chain.

For example, when you create an instance of a class, Dojo calls the

constructor of its superclass before calling constructor of the child

class.

Also, if you add a method to the child class with same name as that of

the superclass, then the method in the child class overrides the

method in the superclass.

5/19/2012 76

Page 77: Complete Dojo

Extending a class

creates a custom.javaworld.ITWorker class that

extends custom.javaworld.Worker.

dojo.declare("custom.javaworld.ITWorker",custom.javaworld.Worker,{

constructor: function(fName, lName){

console.debug("Constructor of com.javaworld.ITWorker");

},

work: function(){

this.inherited(arguments);

console.log("Writing Code");

}

});

var johnDoe = new com.javaworld.ITWorker("John","Doe");

johnDoe.work();

5/19/2012 77

Page 78: Complete Dojo

Cont…

Because we want ITWorker to extend the Worker class, the above

code passes the custom.javaworld.Worker class as the second

argument when declaring the ITWorker class.

Now when you create a new instance of ITWorker using

the new operator, Dojo first invokes the constructor

of Worker class. Also, the ITWorker class's work() method

overrides the Worker class's work() method.

The .inherited() construct to invoke an inherited method of the

superclass.

Here when you call the ITWorker class's work() method, it first

invokes the Worker class's work() method, which prints

"Working" on the console then prints "Writing Code" on the

console.

5/19/2012 78

Page 79: Complete Dojo

Multiple inheritance Dojo allows a class to inherit from multiple classes.

Create a PartTimeMusician class that inherits from both ITWorker and Musician.

dojo.declare("com.javaworld.Musician",null,{

constructor: function(fName, lName){

console.debug("Constructor of com.javaworld.Musician");

},

playMusic: function(){

console.log("Playing Music"); }

});

dojo.declare("com.javaworld.PartTimeMusician",

[com.javaworld.ITWorker,com.javaworld.Musician],{

constructor: function(fName, lName){

console.debug("Constructor of com.javaworld.PartTimeMusician");

}

});

var johnDoe = new com.javaworld.PartTimeMusician("John","Doe");

johnDoe.work();

johnDoe.playMusic(); 5/19/2012 79

Page 80: Complete Dojo

Cont… we pass an array of ITWorker and Musician as the second

argument to the dojo.declare() method while declaring the PartTimeMusician class.

Now when you execute this code it will generate output like this: • Constructor of com.javaworld.Worker called

• Constructor of com.javaworld.ITWorker

• Constructor of com.javaworld.Musician

• Constructor of com.javaworld.PartTimeMusician

• Working

• Writing Code

• Playing Music

As you can see, the constructor of the Worker class, which is the parent of the ITWorker class, is invoked first, followed by the constructor of ITWorker.

The constructor of ITWorker is called before Musician's constructor because, while declaring the PartTimeMusician class, we passed an array of superclasses in which ITWorker was the first argument and Musician was the second argument.

http://dojotoolkit.org/documentation/tutorials/1.6/declare/ 5/19/2012 80

Page 81: Complete Dojo

Overriding methods

A method of a superclass can be extended by declaring an attribute

with the same name.

There is no concept of overloading, as JavaScript ignores any

unexpected arguments and substitutes null for any that are missing.

In Java code, to invoke the overridden method you call the method on

super (that is, super().method Name(arg1, arg1);), but in Dojo you

use the inherited method (this.inherited(arguments);)

The Following Example shows two classes declared,

where child extends parent, overriding its helloWorld method, but

calls inherited to access the function of parent.

5/19/2012 81

Page 82: Complete Dojo

Example

Invoking superclass method in Dojo dojo.declare( "parent", null,

{

helloWorld : function()

{

console.log("parent says 'hello world'");

}

} );

dojo.declare( "child", parent,

{

helloWorld : function()

{

this.inherited(arguments); // Call superclass method...

console.log("child says 'hello world'");

}

} );

var child = new child();

child.helloWorld(); http://www.ibm.com/developerworks/web/librar

y/wa-aj-dojo/ 5/19/2012 82

Page 83: Complete Dojo

Remote Scripting with XHR

Remote scripting is the process of communicating with a server

from a client-side script without requiring a page reload.

•Each methods of remote scripting has advantages and

disadvantages. Although XHR began life as a Microsoft-only

technology, it is now available in all modern browsers.

5/19/2012 83

Page 84: Complete Dojo

Cont…

XHR allows for full control of the HTTP transaction (URL,

headers, content), can use any HTTP method (GET, POST, PUT,

DELETE), and can be executed both synchronously and

asynchronously.

because of the same-origin policy, an XHR object cannot

communicate with a server that resides at a different origin than the

document that contains the script making the service request.

5/19/2012 84

Page 85: Complete Dojo

Making an XMLHttpRequest

Most browsers provide a XMLHttpRequest object that allows you to

make an asynchronous request to the server and get a response

without refreshing the whole page.

But if you try to use the XMLHttpRequest object directly without

using a JavaScript framework such as Dojo, you'll run into problems

such as memory leaks and divergent, browser-specific APIs.

The Dojo toolkit simplifies the use of XMLHttpRequest by providing

a set of wrapper functions for the object.

The wrapper functions address common infrastructural issues by

providing a unified API, cross-browser compatibility, error handling,

data encoding, and much more.

5/19/2012 85

Page 86: Complete Dojo

Cont…

The four wrapper functions all start with xhr (a short form

of XMLHttpRequest):

xhrGet() allows you to make an HTTP GET method call to the server.

xhrPost() allows you to make an HTTP POST method call to the server.

xhrPut() allows you to make an HTTP PUT method call to the server.

xhrDelete() allows you to make an HTTP DELETE method call to the

server.

Dojo also provides a generic xhr() function that takes the name of the

HTTP method that you want to use as an argument and makes the

requested method call.

5/19/2012 86

Page 87: Complete Dojo

dojo.xhrGet

The dojo.xhrGet() function is the cornerstone function of AJAX

development.

Its purpose is to provide an easy to use and consistent interface to

making asynchronous calls to retrieve data.

This makes it much simpler to write cross-browser compatible AJAX

style applications.

This function, in essence, implements making an HTTP 'GET' call.

Limitations dojo.xhrGet (and other functions in the same line: dojo.xhrPost, dojo.xhrDelete,

dojo.xhrPut), are bound by the 'same domain' security policy of the browser.

This means that they can only establish a connection back to the same server that

served the HTML page.

5/19/2012 87

Page 88: Complete Dojo

Ajax XML HttpRequest with Dojo

A Hello world Dojo Ajax example:

The file “data.txt” has a text statement “Welcome to Dojo Ajax!”.

This Web application just downloads the content of this text file, places it in the HTML “div” tag “put_here” placeholder, and displays it.

Assume the dojo core package dojo.js library is installed in the dojo directory in the root directory under webapps in a Web server such as Apache Tomcat.

If you browse this page, the “Welcome to Dojo Ajax” will be displayed in the HTML page.

5/19/2012 88

Page 89: Complete Dojo

Here is the HTML file with a xhrGet Ajax request.

<html>

<head>

<title>Dojo Ajax</title>

<script type="text/javascript" src='dojo/dojo/dojo.js'></script>

<script>

function welcome() {

dojo.xhrGet( {

url: "data.txt",

// The load function is called on successful response from server

// It inserts the response to the HTML div “put_here” placeholder

load: function(response, ioArgs)

{

dojo.byId("put_here").innerHTML = response;

return response;

},

5/19/2012 89

Page 90: Complete Dojo

Contd….

// The error function displays error message if server does not

// respond right

error: function(response, ioArgs)

{

console.error("HTTP status code: ", ioArgs.xhr.status);

return response;

}

});

}

//Invoke the welcome function when dojo starts up

dojo.addOnLoad(welcome);

</script>

</head>

<body>

<div id="put_here" ></div>

</body>

</html>

5/19/2012 90

Page 91: Complete Dojo

Example

One uses Dojo xhrGet function to get data from the server and partially update the DHTML page without refreshing the whole page, just like all Ajax requests do. The other uses Dojo xhrPost method to post the DHTML form data to the server and receives responses back from the server to partiall update the client page.

The next example shows a Dojo xhrPost Ajax request in the following HTML file.

The request is sent to a JSP called response.jsp, which will respond to the Ajax xhrPost form request with a provided user name, and say “Hello <user name>”.

5/19/2012 91

Page 92: Complete Dojo

<html>

<head>

<title>Hello User</title>

<script language="javascript"

src="/dojocore/dojo/dojo.js"></script>

<script language="javascript">

dojo.addOnLoad(function() {

var form = dojo.byId("sampleForm"); // save ref to form

dojo.connect(form, "onsubmit", function(e) {

// connect to, and disable the submit of this form

e.preventDefault();

// post the form with all it's defaults

dojo.xhrPost({

5/19/2012 92

Page 93: Complete Dojo

form: form,

load: function(data) {

// set the form's HTML to be the response

form.innerHTML = data;

}

});

});

});

dojo.require("dijit.form.Button");

</script>

</head>

<body>

<form method="post" id="sampleForm" action="response.jsp">

<h3> Example of using xhrpost</h3><br>

Enter Name: <input type="text" length="20" name="myName"/>

<button type="submit" data-dojo-type="dijit.form.Button"

id="submitButton">Send it!</button>

</form>

<div id='Message'></div>

</body>

</html> 5/19/2012 93

Page 94: Complete Dojo

Response.jsp

<%

String name = request.getParameter("myName");

if (name != null && !name.trim().equals("")) {

out.print("Hello " + name + "!");

} else {

out.print("You didn't enter a name!");

}

%>

5/19/2012 94

Page 95: Complete Dojo

Data Source

5/19/2012 95

A data source is what the name implies, a source that provides data

to something.

In the case of a data store, a data source is where the data store

obtains its data.

A data source can be a database, a REST service, or even a JSON file.

For introductory purposes, we will look at the most simple data

source available, a javascript object.

Page 96: Complete Dojo

Connecting dijit.Tree

5/19/2012 96

dojo.require("dojo.data.ItemFileReadStore"); dojo.require("dijit.Tree");

var storeData = { identifier: 'abbr', label: 'name',

items: [

{ abbr:'ec', name:'Ecuador', capital:'Quito' },

{ abbr:'eg', name:'Egypt', capital:'Cairo' },

{ abbr:'sv', name:'El Salvador', capital:'San Salvador' },

{ abbr:'gq', name:'Equatorial Guinea', capital:'Malabo' },

{ abbr:'er', name:'Eritrea', capital:'Asmara' },

{ abbr:'ee', name:'Estonia', capital:'Tallinn' },

{ abbr:'et', name:'Ethiopia', capital:'Addis Ababa' }

]}

<div data-dojo-type="dojo.data.ItemFileReadStore" data-dojo-props="data:storeData" data-dojo-id="countryStore"></div>

<div data-dojo-type="dijit.tree.ForestStoreModel" data-dojo-id="countryModel"

data-dojo-props="store:countryStore, rootId:'Countries', rootLabel:'Countries'"></div>

<div data-dojo-type="dijit.Tree" data-dojo-props="model:countryModel"></div>

Page 97: Complete Dojo

5/19/2012 97

In the above example: The data source is the above javascript object

Each item is a country, and each item has three attributes: name, abbr, and capital.

The abbr attribute is an identifier. Each country has a different abbr for unique look up.

This is a simple, but powerful, way to represent data in the browser. It can also be quickly converted to a text format called JavaScript Object Notation (JSON).

The JSON format can be stored as files on your server and loaded via xhr calls.

dojo.data.ItemFileReadStore allows for the data to be defined in browser as an object, or from a JSON file of the same format.

The example shows how a datastore can be used to load the data and how widgets that are dojo.data aware can make use of it to display it easily.

Page 98: Complete Dojo

dojo.data.ItemFileReadStore

5/19/2012 98

Dojo core provides an implementation of a read-only

datastore, ItemFileReadStore.

This store reads the JSON structured contents from an

http endpoint (service or URL), or from an in-memory

JavaScript object, and stores all the items in-memory for

simple and quick access.

ItemFileReadStore is designed to allow for flexibility in

how it represents item hierarchy, references, and custom

data types.

It also provides options for which an attribute can act as the

unique identifier, and which attribute can be used as a

general label for an item. http://dojotoolkit.org/reference-guide/1.7/quickstart/data/usingdatastores.html

Page 99: Complete Dojo

Custom Widgets

5/19/2012 99

Let us create a simple widget that will just say "Hello, World!“.

First, Within “dojocore/Custom” sub-folder, create a

file CustomWidget.js with the following contents: dojo.provide('Custom.CustomWidget');

dojo.require('dijit._Widget');

dojo.declare("Custom.CustomWidget", dijit._Widget,

{

postCreate : function()

{

this.domNode.innerHTML = 'Hello, World!';

}

});

Page 100: Complete Dojo

Cont…

5/19/2012 100

One of the more important functions of the

object dijit._Widget is postCreate.

We override the method to provide our implementation and that is

to simply set theinnerHTML of the container to the text Hello,

World!.

Now that we have got the widget, we do not know how and if it

works.

So, let's just write a simple test page (HTML) to use it. Create a file

Web Pages/custom-widget-test.html with the following contents.

Page 101: Complete Dojo

5/19/2012 101

<html>

<head>

<title>Custom Widget Test</title>

<script type="text/javascript" language='javascript'

src="dojocore/dojo/dojo.js" djConfig="isDebug: true,

parseOnLoad: true"></script>

<script type='text/javascript' language='javascript'>

dojo.require('dijit.form.Button');

dojo.require(‘Custom.CustomWidget');

</script>

</head>

<body> <div id='w1' dojoType=‘Custom.CustomWidget'></div>

</body>

</html>

Page 102: Complete Dojo

Customizing the Widget

5/19/2012 102

The next step is to customize the Hello, World! with a user defined content.

Let's say that the default value of the content to be displayed is Hello, World!. To this effect, update the CustomWidget.js as follows:

dojo.declare(“Custom.CustomWidget", dijit._Widget, { text: 'Hello, World!',

postCreate : function() {

this.domNode.innerHTML = this.text;

}

});

Simultaneously, we update the custom-widget-test.html file to as follows:

<body> <div id='w1' text='Hello, Java World!' dojoType=‘Custom.CustomWidget'></div> </body>

Page 103: Complete Dojo

Templated Widgets

5/19/2012 103

Dijit sub-framework in Dojo Toolkit provides a support for

templated widgets through the object dijit._Templated.

Well, we do not inherit this but use as a mixin and

choosedijit._Widget as the parent object.

_TemplatedMixin implements buildRendering() for you, and all you

have to do is specify a template i.e, an HTML fragment, that specifies

the DOM for the widget.

http://livedocs.dojotoolkit.org/quickstart/writingWidgets

Page 104: Complete Dojo

104 5/19/2012

Page 106: Complete Dojo

106 5/19/2012