SlideShare a Scribd company logo
1 of 106
Download to read offline
Dojo Tutorial




                     Girish Srivastava
                    girish.srivastava@vtindia.net
1                                        5/19/2012
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
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
 3 application.                                             5/19/2012
4   5/19/2012
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
6   5/19/2012
7   5/19/2012
8   5/19/2012
DOJO Core




9               5/19/2012
What Is Dijit?




10                    5/19/2012
11   5/19/2012
12   5/19/2012
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
                                                                    13
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
                                                                  14
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
                                                                                    15
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
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
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
•YUI(TheYahoo! 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
• 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
 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
22   5/19/2012
23   5/19/2012
24   5/19/2012
25   5/19/2012
Loading Dojo ToolKit…


26                       5/19/2012
27   5/19/2012
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
29   5/19/2012
30   5/19/2012
Themes and Theming
 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:


31                                                                               5/19/2012
Example
 <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>
32                http://dojotoolkit.org/reference-guide/1.7/dijit/themes.html   5/19/2012
Dojo Hello World
     <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>
33   </html>                                                                  5/19/2012
 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
 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
 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
Configuring the Dojo runtime
  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.

37                                                             5/19/2012
 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.
38                                                                  5/19/2012
•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>

39                                                              5/19/2012
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);
       }




40                                                                          5/19/2012
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);
            }


41                                                                    5/19/2012
Continue with…




42                    5/19/2012
43   5/19/2012
JavaScript Object Oriented Feature
 <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>
44                                                                 5/19/2012
Object-Oriented Programming

 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.




 45                                                                5/19/2012
 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.




46                                                                                 5/19/2012
Prototype-based OOP
 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.

47                                                               5/19/2012
A basic object prototype in JavaScript
          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 }.
48                                                       5/19/2012
Adding a method to the prototype
          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 }.


49                                                           5/19/2012
Example
 <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;
                          }

50                                                       5/19/2012
Example Cont…
                      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>
51                                                                           5/19/2012
Functions

      functions are objects
      they have properties
      they have methods
      can be copied, deleted, augmented...
      special feature: invokable




52                                            5/19/2012
Functions

     function boo(what) {
        return what;
     }
      or
     var boo = function(what) {
        return what;
     };




53                                5/19/2012
Functions

     function boo(what) {
        return what;
     }
      or
     var boo = function bootoo(what) {
        return what;
     };




54                                       5/19/2012
Return value
      all functions return a value
      if they don't explicitly, they return undefined
       implicitly
      functions can return other functions




55                                                       5/19/2012
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




56                                                        5/19/2012
Constructor functions

     var Person = function(name) {
          this.name = name;
          this.speaks = 'fr';
          this.say = function() {
         return "Je m'appelle " +
      this.name;
          };
     };


57                                   5/19/2012
An object created with constructor
     >>>
           var julien = new Person("Julien");
     >>>
          julien.say();
     "Je m'appelle Julien"




58                                        5/19/2012
prototype
      a property of the function objects


     >>> var boo = function(){};
     >>> typeof boo.prototype
     "object"




59                                          5/19/2012
Prototypes can be augmented
     >>> boo.prototype.a = 1;
     >>> boo.prototype.sayAh =
      function(){};




60                                 5/19/2012
Prototypes can be overwritten
     >>> boo.prototype = {a: 1, b: 2};




61                                       5/19/2012
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;
     }


62                                                   5/19/2012
How is the prototype used?

     >>> var dude = new Person('dude');
     >>> dude.name;
     "dude"
     >>> dude.say();
     "dude"




63                                        5/19/2012
Own properties vs. prototype’s
     >>> dude.hasOwnProperty('name');
     true
     >>> dude.hasOwnProperty('say');
     false




64                                      5/19/2012
The prototype chain




65                         5/19/2012
It’s alive!
     >>> typeof dude.numlegs
     "undefined"
     >>> Person.prototype.numlegs = 2;
     >>> dude.numlegs
     2




66                                       5/19/2012
Inheritance


67                 5/19/2012
Inheritance via the prototype
     >>> var Dad = function()
           {
           this.family = “Rahul";
           };
     >>> var Kid = function(){};
     >>> Kid.prototype = new Dad();
     >>> var billy = new Kid();
     >>> billy.family
     “Rahul"




68                                   5/19/2012
Inherit one more time
     >>> var GrandKid = function(){};
     >>> GrandKid.prototype = billy;
     >>> var jill = new GrandKid();
     >>> jill.family
     “Rahul"




69                                      5/19/2012
Inheritance…
     >>> jill.hasOwnProperty('family')
     false
     >>> jill.__proto__.hasOwnProperty('family')
     false
     >>> jill.__proto__.__proto__.hasOwnProperty('family')
     true




70                                                    5/19/2012
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.



71                                                               5/19/2012
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.

72                                                               5/19/2012
Cont…
 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);


73                                                               5/19/2012
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.

74                                                           5/19/2012
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);
75                                                                    5/19/2012
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.




76                                                                5/19/2012
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();
  77                                                           5/19/2012
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.
78                                                         5/19/2012
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();
 79                                                                       5/19/2012
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.
80     http://dojotoolkit.org/documentation/tutorials/1.6/declare/         5/19/2012
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.




81                                                            5/19/2012
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
82                                         y/wa-aj-dojo/                        5/19/2012
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.




83                                                                 5/19/2012
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.




84                                                             5/19/2012
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.


85                                                            5/19/2012
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.



86                                                                    5/19/2012
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.


87                                                                               5/19/2012
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.




88                                                                     5/19/2012
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;
                },


89                                                                          5/19/2012
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>
90                                                                   5/19/2012
    </html>
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>”.




91                                                                          5/19/2012
<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({
92                                                     5/19/2012
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>                                                        5/19/2012
93
  </html>
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!");
       }
     %>
94                                               5/19/2012
Data Source

 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.




95                                                             5/19/2012
Connecting dijit.Tree
  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>
96                                                                            5/19/2012
 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.
97                                                                5/19/2012
dojo.data.ItemFileReadStore
       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.
98   http://dojotoolkit.org/reference-guide/1.7/quickstart/data/usingdatastores.html   5/19/2012
Custom Widgets
 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!';
         }
         });




99                                                              5/19/2012
Cont…
 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.




100                                                             5/19/2012
<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>



101                                                               5/19/2012
Customizing the Widget
 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>
102                                                                    5/19/2012
Templated Widgets
 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.




103      http://livedocs.dojotoolkit.org/quickstart/writingWidgets   5/19/2012
104   5/19/2012
References:
 http://ofps.oreilly.com/titles/9780596516482/index.html
 http://livedocs.dojotoolkit.org/dojo/request/
 http://dojotoolkit.org/documentation/tutorials/1.6/declare/
 http://www.javaworld.com/javaworld/jw-01-2009/jw-01-
      introduction-to-dojo-1.html?page=1
     http://dojotoolkit.org/reference-guide/1.7/dojo/data.html#dojo-
      data
     http://www.java2s.com/Tutorial/JavaScript/0570__Dojo-
      toolkit/Catalog0570__Dojo-toolkit.htm
     http://www.roseindia.net/dojo/index.shtml
     http://www.json.org/

105                                                          5/19/2012
106   5/19/2012

More Related Content

What's hot

Hotwire: How To Build Reactive Rails Applications Without Javascript
Hotwire: How To Build Reactive Rails Applications Without JavascriptHotwire: How To Build Reactive Rails Applications Without Javascript
Hotwire: How To Build Reactive Rails Applications Without JavascriptMix & Go
 
React.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMReact.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMJimit Shah
 
Django and Neo4j - Domain modeling that kicks ass
Django and Neo4j - Domain modeling that kicks assDjango and Neo4j - Domain modeling that kicks ass
Django and Neo4j - Domain modeling that kicks assTobias Lindaaker
 
Android studio installation
Android studio installationAndroid studio installation
Android studio installationPoojaBele1
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjsmanojbkalla
 
Change date format in odoo
Change date format in odooChange date format in odoo
Change date format in odoodeeps virzoteck
 
Simple file sharing system
Simple file sharing systemSimple file sharing system
Simple file sharing systemWilliam Phoenix
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.jsDoug Neiner
 
Deep dive into Vue.js
Deep dive into Vue.jsDeep dive into Vue.js
Deep dive into Vue.js선협 이
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django frameworkflapiello
 
Abbyy Flexicapture Basic Certification
Abbyy Flexicapture Basic CertificationAbbyy Flexicapture Basic Certification
Abbyy Flexicapture Basic CertificationShubham Sidana
 
ADF Bindings & Data Controls
ADF Bindings & Data ControlsADF Bindings & Data Controls
ADF Bindings & Data ControlsRohan Walia
 
Mating a hinge assembly in solidworks
Mating a hinge assembly in solidworksMating a hinge assembly in solidworks
Mating a hinge assembly in solidworksCaksback
 
Developing accessible android applications
Developing accessible android applicationsDeveloping accessible android applications
Developing accessible android applicationsRenato Iwashima
 

What's hot (16)

Hotwire: How To Build Reactive Rails Applications Without Javascript
Hotwire: How To Build Reactive Rails Applications Without JavascriptHotwire: How To Build Reactive Rails Applications Without Javascript
Hotwire: How To Build Reactive Rails Applications Without Javascript
 
React.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMReact.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOM
 
Django and Neo4j - Domain modeling that kicks ass
Django and Neo4j - Domain modeling that kicks assDjango and Neo4j - Domain modeling that kicks ass
Django and Neo4j - Domain modeling that kicks ass
 
Android studio installation
Android studio installationAndroid studio installation
Android studio installation
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
 
Change date format in odoo
Change date format in odooChange date format in odoo
Change date format in odoo
 
Simple file sharing system
Simple file sharing systemSimple file sharing system
Simple file sharing system
 
Fiverr
FiverrFiverr
Fiverr
 
Angular 8
Angular 8 Angular 8
Angular 8
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.js
 
Deep dive into Vue.js
Deep dive into Vue.jsDeep dive into Vue.js
Deep dive into Vue.js
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django framework
 
Abbyy Flexicapture Basic Certification
Abbyy Flexicapture Basic CertificationAbbyy Flexicapture Basic Certification
Abbyy Flexicapture Basic Certification
 
ADF Bindings & Data Controls
ADF Bindings & Data ControlsADF Bindings & Data Controls
ADF Bindings & Data Controls
 
Mating a hinge assembly in solidworks
Mating a hinge assembly in solidworksMating a hinge assembly in solidworks
Mating a hinge assembly in solidworks
 
Developing accessible android applications
Developing accessible android applicationsDeveloping accessible android applications
Developing accessible android applications
 

Viewers also liked

How dojo works
How dojo worksHow dojo works
How dojo worksAmit Tyagi
 
The Dojo Toolkit An Introduction
The Dojo Toolkit   An IntroductionThe Dojo Toolkit   An Introduction
The Dojo Toolkit An IntroductionJeff Fox
 
Angularjs vs Dojo toolkit | SuperSpeaker@CodeCamp Iasi 2014
Angularjs vs Dojo toolkit | SuperSpeaker@CodeCamp Iasi 2014Angularjs vs Dojo toolkit | SuperSpeaker@CodeCamp Iasi 2014
Angularjs vs Dojo toolkit | SuperSpeaker@CodeCamp Iasi 2014Endava
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoFu Cheng
 
Rich internet application development using the dojo toolkit
Rich internet application development using the dojo toolkitRich internet application development using the dojo toolkit
Rich internet application development using the dojo toolkitalexklaeser
 
Solve 3 Enterprise Storage Problems Today
Solve 3 Enterprise Storage Problems TodaySolve 3 Enterprise Storage Problems Today
Solve 3 Enterprise Storage Problems TodayStephen Foskett
 
Integrated Lifecycle Marketing Workshop: Emerging Channels for Email List Bui...
Integrated Lifecycle Marketing Workshop: Emerging Channels for Email List Bui...Integrated Lifecycle Marketing Workshop: Emerging Channels for Email List Bui...
Integrated Lifecycle Marketing Workshop: Emerging Channels for Email List Bui...Vivastream
 
Renesas RL78 The True Low Power Microcontroller Platform
 Renesas RL78 The True Low Power Microcontroller Platform Renesas RL78 The True Low Power Microcontroller Platform
Renesas RL78 The True Low Power Microcontroller PlatformRenesas Electronics Corporation
 
How to refill canon color cartridge 241
How to refill canon color cartridge 241How to refill canon color cartridge 241
How to refill canon color cartridge 241printerfillingstation
 
An Introduction to Faye
An Introduction to FayeAn Introduction to Faye
An Introduction to FayeDarren Oakley
 
Summary -Fish
Summary -FishSummary -Fish
Summary -FishGMR Group
 
Intermediate Colors
Intermediate ColorsIntermediate Colors
Intermediate Colorsartoutman
 
How to Make the Inc 500 List
How to Make the Inc 500 ListHow to Make the Inc 500 List
How to Make the Inc 500 ListHubSpot
 
Analytics Solutions from SAP
Analytics Solutions from SAPAnalytics Solutions from SAP
Analytics Solutions from SAPSAP Analytics
 
Friendship’s coupons
Friendship’s couponsFriendship’s coupons
Friendship’s couponsClarice J
 
American Greetings interview questions and answers
American Greetings interview questions and answersAmerican Greetings interview questions and answers
American Greetings interview questions and answersroggerring
 

Viewers also liked (20)

Dojo tutorial
Dojo tutorialDojo tutorial
Dojo tutorial
 
How dojo works
How dojo worksHow dojo works
How dojo works
 
Dojo toolkit
Dojo toolkitDojo toolkit
Dojo toolkit
 
The Dojo Toolkit An Introduction
The Dojo Toolkit   An IntroductionThe Dojo Toolkit   An Introduction
The Dojo Toolkit An Introduction
 
Angularjs vs Dojo toolkit | SuperSpeaker@CodeCamp Iasi 2014
Angularjs vs Dojo toolkit | SuperSpeaker@CodeCamp Iasi 2014Angularjs vs Dojo toolkit | SuperSpeaker@CodeCamp Iasi 2014
Angularjs vs Dojo toolkit | SuperSpeaker@CodeCamp Iasi 2014
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
 
Rich internet application development using the dojo toolkit
Rich internet application development using the dojo toolkitRich internet application development using the dojo toolkit
Rich internet application development using the dojo toolkit
 
Ambienti di virtualizzazione
Ambienti di virtualizzazioneAmbienti di virtualizzazione
Ambienti di virtualizzazione
 
Solve 3 Enterprise Storage Problems Today
Solve 3 Enterprise Storage Problems TodaySolve 3 Enterprise Storage Problems Today
Solve 3 Enterprise Storage Problems Today
 
Integrated Lifecycle Marketing Workshop: Emerging Channels for Email List Bui...
Integrated Lifecycle Marketing Workshop: Emerging Channels for Email List Bui...Integrated Lifecycle Marketing Workshop: Emerging Channels for Email List Bui...
Integrated Lifecycle Marketing Workshop: Emerging Channels for Email List Bui...
 
Renesas RL78 The True Low Power Microcontroller Platform
 Renesas RL78 The True Low Power Microcontroller Platform Renesas RL78 The True Low Power Microcontroller Platform
Renesas RL78 The True Low Power Microcontroller Platform
 
How to refill canon color cartridge 241
How to refill canon color cartridge 241How to refill canon color cartridge 241
How to refill canon color cartridge 241
 
Enterprise TEPPCO Pipeline System Map
Enterprise TEPPCO Pipeline System MapEnterprise TEPPCO Pipeline System Map
Enterprise TEPPCO Pipeline System Map
 
An Introduction to Faye
An Introduction to FayeAn Introduction to Faye
An Introduction to Faye
 
Summary -Fish
Summary -FishSummary -Fish
Summary -Fish
 
Intermediate Colors
Intermediate ColorsIntermediate Colors
Intermediate Colors
 
How to Make the Inc 500 List
How to Make the Inc 500 ListHow to Make the Inc 500 List
How to Make the Inc 500 List
 
Analytics Solutions from SAP
Analytics Solutions from SAPAnalytics Solutions from SAP
Analytics Solutions from SAP
 
Friendship’s coupons
Friendship’s couponsFriendship’s coupons
Friendship’s coupons
 
American Greetings interview questions and answers
American Greetings interview questions and answersAmerican Greetings interview questions and answers
American Greetings interview questions and answers
 

Similar to Complete Dojo

Dojo Toolkit from a Flex developer's perspective
Dojo Toolkit from a Flex developer's perspectiveDojo Toolkit from a Flex developer's perspective
Dojo Toolkit from a Flex developer's perspectivecjolif
 
Dojo and Zend Framework
Dojo and Zend  FrameworkDojo and Zend  Framework
Dojo and Zend FrameworkKuldeep Singh
 
Dojo mobile web5-2013
Dojo mobile web5-2013Dojo mobile web5-2013
Dojo mobile web5-2013cjolif
 
Enabling the mobile Web for a Dojo component
Enabling the mobile Web for a Dojo componentEnabling the mobile Web for a Dojo component
Enabling the mobile Web for a Dojo componentcjolif
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slideshelenmga
 
Starting with jQuery
Starting with jQueryStarting with jQuery
Starting with jQueryAnil Kumar
 
jQuery - the world's most popular java script library comes to XPages
jQuery - the world's most popular java script library comes to XPagesjQuery - the world's most popular java script library comes to XPages
jQuery - the world's most popular java script library comes to XPagesMark Roden
 
jQuery: The World's Most Popular JavaScript Library Comes to XPages
jQuery: The World's Most Popular JavaScript Library Comes to XPagesjQuery: The World's Most Popular JavaScript Library Comes to XPages
jQuery: The World's Most Popular JavaScript Library Comes to XPagesTeamstudio
 
Design Pattern presentation
Design Pattern presentationDesign Pattern presentation
Design Pattern presentationhoanhtran
 
Introduction To Dojo
Introduction To DojoIntroduction To Dojo
Introduction To Dojoyoavrubin
 
Building Dojo in the Cloud
Building Dojo in the CloudBuilding Dojo in the Cloud
Building Dojo in the CloudJames Thomas
 
#1 - HTML5 Overview
#1 - HTML5 Overview#1 - HTML5 Overview
#1 - HTML5 Overviewiloveigloo
 
Social Connections VI — IBM Connections Extensions and Themes Demystified
Social Connections VI — IBM Connections Extensions and Themes DemystifiedSocial Connections VI — IBM Connections Extensions and Themes Demystified
Social Connections VI — IBM Connections Extensions and Themes DemystifiedClaudio Procida
 
Introduction to android studio 2.0 and data binding library
Introduction to android studio 2.0 and data binding libraryIntroduction to android studio 2.0 and data binding library
Introduction to android studio 2.0 and data binding libraryKaushal Dhruw
 
Designing Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDIDesigning Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDIMichel Graciano
 
OAE Developer Bootcamp
OAE Developer BootcampOAE Developer Bootcamp
OAE Developer BootcampBert Pareyn
 

Similar to Complete Dojo (20)

Dojo Toolkit from a Flex developer's perspective
Dojo Toolkit from a Flex developer's perspectiveDojo Toolkit from a Flex developer's perspective
Dojo Toolkit from a Flex developer's perspective
 
Dojo training
Dojo trainingDojo training
Dojo training
 
Test02
Test02Test02
Test02
 
DOJO
DOJO DOJO
DOJO
 
Dojo and Zend Framework
Dojo and Zend  FrameworkDojo and Zend  Framework
Dojo and Zend Framework
 
Dojo mobile web5-2013
Dojo mobile web5-2013Dojo mobile web5-2013
Dojo mobile web5-2013
 
Enabling the mobile Web for a Dojo component
Enabling the mobile Web for a Dojo componentEnabling the mobile Web for a Dojo component
Enabling the mobile Web for a Dojo component
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slides
 
Starting with jQuery
Starting with jQueryStarting with jQuery
Starting with jQuery
 
jQuery - the world's most popular java script library comes to XPages
jQuery - the world's most popular java script library comes to XPagesjQuery - the world's most popular java script library comes to XPages
jQuery - the world's most popular java script library comes to XPages
 
jQuery: The World's Most Popular JavaScript Library Comes to XPages
jQuery: The World's Most Popular JavaScript Library Comes to XPagesjQuery: The World's Most Popular JavaScript Library Comes to XPages
jQuery: The World's Most Popular JavaScript Library Comes to XPages
 
Design Pattern presentation
Design Pattern presentationDesign Pattern presentation
Design Pattern presentation
 
Introduction To Dojo
Introduction To DojoIntroduction To Dojo
Introduction To Dojo
 
Fewd week4 slides
Fewd week4 slidesFewd week4 slides
Fewd week4 slides
 
Building Dojo in the Cloud
Building Dojo in the CloudBuilding Dojo in the Cloud
Building Dojo in the Cloud
 
#1 - HTML5 Overview
#1 - HTML5 Overview#1 - HTML5 Overview
#1 - HTML5 Overview
 
Social Connections VI — IBM Connections Extensions and Themes Demystified
Social Connections VI — IBM Connections Extensions and Themes DemystifiedSocial Connections VI — IBM Connections Extensions and Themes Demystified
Social Connections VI — IBM Connections Extensions and Themes Demystified
 
Introduction to android studio 2.0 and data binding library
Introduction to android studio 2.0 and data binding libraryIntroduction to android studio 2.0 and data binding library
Introduction to android studio 2.0 and data binding library
 
Designing Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDIDesigning Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDI
 
OAE Developer Bootcamp
OAE Developer BootcampOAE Developer Bootcamp
OAE Developer Bootcamp
 

More from Girish Srivastava (8)

My tableau
My tableauMy tableau
My tableau
 
IBM Pure Data System for Analytics (Netezza)
IBM Pure Data System for Analytics (Netezza)IBM Pure Data System for Analytics (Netezza)
IBM Pure Data System for Analytics (Netezza)
 
Jquery
JqueryJquery
Jquery
 
Jscript part2
Jscript part2Jscript part2
Jscript part2
 
Extjs
ExtjsExtjs
Extjs
 
Jive
JiveJive
Jive
 
Jscript part1
Jscript part1Jscript part1
Jscript part1
 
Cgi
CgiCgi
Cgi
 

Recently uploaded

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 

Recently uploaded (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Complete Dojo

  • 1. Dojo Tutorial Girish Srivastava girish.srivastava@vtindia.net 1 5/19/2012
  • 2. 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
  • 3. 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 3 application. 5/19/2012
  • 4. 4 5/19/2012
  • 5. 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
  • 6. 6 5/19/2012
  • 7. 7 5/19/2012
  • 8. 8 5/19/2012
  • 9. DOJO Core 9 5/19/2012
  • 10. What Is Dijit? 10 5/19/2012
  • 11. 11 5/19/2012
  • 12. 12 5/19/2012
  • 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 13
  • 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 14
  • 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 15
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. •YUI(TheYahoo! 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
  • 20. • 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
  • 21.  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
  • 22. 22 5/19/2012
  • 23. 23 5/19/2012
  • 24. 24 5/19/2012
  • 25. 25 5/19/2012
  • 27. 27 5/19/2012
  • 28. 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
  • 29. 29 5/19/2012
  • 30. 30 5/19/2012
  • 31. Themes and Theming  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: 31 5/19/2012
  • 32. Example  <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> 32 http://dojotoolkit.org/reference-guide/1.7/dijit/themes.html 5/19/2012
  • 33. Dojo Hello World <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> 33 </html> 5/19/2012
  • 34.  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
  • 35.  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
  • 36.  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
  • 37. Configuring the Dojo runtime  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. 37 5/19/2012
  • 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. 38 5/19/2012
  • 39. •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> 39 5/19/2012
  • 40. 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); } 40 5/19/2012
  • 41. 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); } 41 5/19/2012
  • 42. Continue with… 42 5/19/2012
  • 43. 43 5/19/2012
  • 44. JavaScript Object Oriented Feature  <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> 44 5/19/2012
  • 45. Object-Oriented Programming  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. 45 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. 46 5/19/2012
  • 47. Prototype-based OOP  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. 47 5/19/2012
  • 48. A basic object prototype in JavaScript 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 }. 48 5/19/2012
  • 49. Adding a method to the prototype 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 }. 49 5/19/2012
  • 50. Example  <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; } 50 5/19/2012
  • 51. Example Cont… 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> 51 5/19/2012
  • 52. Functions  functions are objects  they have properties  they have methods  can be copied, deleted, augmented...  special feature: invokable 52 5/19/2012
  • 53. Functions function boo(what) { return what; }  or var boo = function(what) { return what; }; 53 5/19/2012
  • 54. Functions function boo(what) { return what; }  or var boo = function bootoo(what) { return what; }; 54 5/19/2012
  • 55. Return value  all functions return a value  if they don't explicitly, they return undefined implicitly  functions can return other functions 55 5/19/2012
  • 56. 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 56 5/19/2012
  • 57. Constructor functions var Person = function(name) { this.name = name; this.speaks = 'fr'; this.say = function() { return "Je m'appelle " + this.name; }; }; 57 5/19/2012
  • 58. An object created with constructor >>> var julien = new Person("Julien"); >>> julien.say(); "Je m'appelle Julien" 58 5/19/2012
  • 59. prototype  a property of the function objects >>> var boo = function(){}; >>> typeof boo.prototype "object" 59 5/19/2012
  • 60. Prototypes can be augmented >>> boo.prototype.a = 1; >>> boo.prototype.sayAh = function(){}; 60 5/19/2012
  • 61. Prototypes can be overwritten >>> boo.prototype = {a: 1, b: 2}; 61 5/19/2012
  • 62. 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; } 62 5/19/2012
  • 63. How is the prototype used? >>> var dude = new Person('dude'); >>> dude.name; "dude" >>> dude.say(); "dude" 63 5/19/2012
  • 64. Own properties vs. prototype’s >>> dude.hasOwnProperty('name'); true >>> dude.hasOwnProperty('say'); false 64 5/19/2012
  • 66. It’s alive! >>> typeof dude.numlegs "undefined" >>> Person.prototype.numlegs = 2; >>> dude.numlegs 2 66 5/19/2012
  • 67. Inheritance 67 5/19/2012
  • 68. Inheritance via the prototype >>> var Dad = function() { this.family = “Rahul"; }; >>> var Kid = function(){}; >>> Kid.prototype = new Dad(); >>> var billy = new Kid(); >>> billy.family “Rahul" 68 5/19/2012
  • 69. Inherit one more time >>> var GrandKid = function(){}; >>> GrandKid.prototype = billy; >>> var jill = new GrandKid(); >>> jill.family “Rahul" 69 5/19/2012
  • 70. Inheritance… >>> jill.hasOwnProperty('family') false >>> jill.__proto__.hasOwnProperty('family') false >>> jill.__proto__.__proto__.hasOwnProperty('family') true 70 5/19/2012
  • 71. 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. 71 5/19/2012
  • 72. 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. 72 5/19/2012
  • 73. Cont…  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); 73 5/19/2012
  • 74. 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. 74 5/19/2012
  • 75. 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); 75 5/19/2012
  • 76. 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. 76 5/19/2012
  • 77. 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(); 77 5/19/2012
  • 78. 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. 78 5/19/2012
  • 79. 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(); 79 5/19/2012
  • 80. 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. 80 http://dojotoolkit.org/documentation/tutorials/1.6/declare/ 5/19/2012
  • 81. 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. 81 5/19/2012
  • 82. 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 82 y/wa-aj-dojo/ 5/19/2012
  • 83. 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. 83 5/19/2012
  • 84. 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. 84 5/19/2012
  • 85. 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. 85 5/19/2012
  • 86. 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. 86 5/19/2012
  • 87. 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. 87 5/19/2012
  • 88. 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. 88 5/19/2012
  • 89. 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; }, 89 5/19/2012
  • 90. 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> 90 5/19/2012 </html>
  • 91. 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>”. 91 5/19/2012
  • 92. <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({ 92 5/19/2012
  • 93. 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> 5/19/2012 93 </html>
  • 94. 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!"); } %> 94 5/19/2012
  • 95. Data Source  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. 95 5/19/2012
  • 96. Connecting dijit.Tree  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> 96 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. 97 5/19/2012
  • 98. dojo.data.ItemFileReadStore  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. 98 http://dojotoolkit.org/reference-guide/1.7/quickstart/data/usingdatastores.html 5/19/2012
  • 99. Custom Widgets  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!'; } }); 99 5/19/2012
  • 100. Cont…  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. 100 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> 101 5/19/2012
  • 102. Customizing the Widget  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> 102 5/19/2012
  • 103. Templated Widgets  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. 103 http://livedocs.dojotoolkit.org/quickstart/writingWidgets 5/19/2012
  • 104. 104 5/19/2012
  • 105. References:  http://ofps.oreilly.com/titles/9780596516482/index.html  http://livedocs.dojotoolkit.org/dojo/request/  http://dojotoolkit.org/documentation/tutorials/1.6/declare/  http://www.javaworld.com/javaworld/jw-01-2009/jw-01- introduction-to-dojo-1.html?page=1  http://dojotoolkit.org/reference-guide/1.7/dojo/data.html#dojo- data  http://www.java2s.com/Tutorial/JavaScript/0570__Dojo- toolkit/Catalog0570__Dojo-toolkit.htm  http://www.roseindia.net/dojo/index.shtml  http://www.json.org/ 105 5/19/2012
  • 106. 106 5/19/2012