JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Use dojo/keys For Key Press Events in DOJO

October 9, 2013 by Krishna Srinivasan Leave a Comment

If you are working in JavaScript, getting the key press events is necessary to perform any user initiated operations. DOJO provides dojo/keys module to perform all the key events. dojo/keys module defines the constants for each type of key with the corresponding key code. This helps us to import this module and directly use it in our code. Almost all the important keys are defined in this module. Look at the below example to understand how to use this module to capture the key events.

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
var dojoConfig = {
baseUrl : "src",
packages : [ {
name : "dojo",
location : "dojo"
}, {
name : "dijit",
location : "dijit"
}, {
name : "dojox",
location : "dojox"
}, {
name : "app",
location : "app"
}, ],
parseOnLoad : true,
async : true
};
</script>
<script src="src/dojo/dojo.js"></script>
<script>
require(["dojo/on",
"dojo/keys",
"dojo/domReady!"],
function(on, keys, dom){
on(document, "keyup", function(event){
alert (event.keyCode);
switch (event.keyCode)
{
case keys.UP_ARROW:
alert ("Up Arrow Pressed!!");
break;
case keys.DOWN_ARROW:
alert ("Down Arrow Pressed!!");
break;
case keys.ENTER:
alert ("Enter Pressed!!");
break;
}
});
});
</script>
</head>
<body>
<h1>Enter Value</h1>
<input type="text" id="keyCode" size="2">
</body>
</html>
[/code]

The above example is easy to understand how to capture the key press events on DOJO application.

Filed Under: DOJO Tagged With: dojotoolkit

Working With dojo/dom-construct – DOM construction API in DOJO

October 9, 2013 by Krishna Srinivasan Leave a Comment

In my previous article I have explained about searching through dom tree using dojo.query. That is very helpful for searching any node in the tree by passing the ID or CLASS names in method parameters. But, I have not explained about how to manipulate the DOM structure. This article focuses more on manipulating the dom tree as you need. In most of the cases, we have to update the dom tree dynamically to reflect the response from the server. It is easy to update any part of the web page with the help of DOJO APIs. DOJO provides dojo/dom-construct to retrieve the DOM elements and manipulate it. This API has several methods and features that is easy to use for the complex operations. dojo/dom-construct stands for DOM construction API.

Example Listing of dojo/dom-construct : 1

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
var dojoConfig = {
baseUrl : "src",
packages : [ {
name : "dojo",
location : "dojo"
}, {
name : "dijit",
location : "dijit"
}, {
name : "dojox",
location : "dojox"
}, {
name : "app",
location : "app"
}, ],
parseOnLoad : true,
async : true
};
</script>
<script src="src/dojo/dojo.js"></script>
<script>
require(["dojo/dom-construct",
"dojo/dom-attr",
"dojo/dom",
"dojo/on",
"dojo/domReady!"],
function(domConstruct,domAttr, dom, on){
var i=0;
//1
on(dom.byId("btn1"), "click", function(){
i = i + 1;
var row = domConstruct.toDom("<tr><td>Test Row " + i + " </td></tr>");
domConstruct.place(row, "tableRow");
});
//2
on(dom.byId("btn2"), "click", function(){
var row = domConstruct.toDom("<div>Placed After Second Element</div>");
domConstruct.place(row, dom.byId("second"),"after");
});
//3
on(dom.byId("btn3"), "click", function(){
var row = domConstruct.toDom("<div>Replaced Third Node With This node!!</div>");
domConstruct.place(row, dom.byId("third"),"replace");
});
//4
on(dom.byId("btn4"), "click", function(){
var row = domConstruct.toDom("<div>Created Node!!</div>");
domConstruct.create(row, {id:"createNode",style:{color:"blue"}},
dom.byId("third"),"after");
});
//5
on(dom.byId("btn5"), "click", function(){
domAttr.set(dom.byId("createNode"), "style",{color:"red"});
});
});
</script>
</head>
<body>
<button id="btn1" type="button">Add a row</button>
<button id="btn2" type="button">Add After Node Second</button>
<button id="btn3" type="button">Replace Third Node</button><br>
<button id="btn4" type="button">Create New Node</button>
<button id="btn5" type="button">Change Attributes</button>

<table>
<thead><tr><th>Description Column</th></tr></thead>
<tbody id="tableRow">
<tr><td></td></tr>
</tbody>
</table>
<div id="second">Second</div>
<div id="third">Third</div>
</body>
</html>
[/code]

The above code snippet is the complete example to demonstrate the various methods and parameters associated with dojo/dom-construct API. domConstruct.toDom is used for creating the DOM element for a given HTML fragment. This is the common method used across this example for creating the new nodes to DOM tree. The following points are detailed explanations for the above example.

  1. domConstruct.place is node placement utility method. Using this method, we can place the node anywhere in the DOM tree. This method takes the two parameters. This method takes three parameters. First parameter is the HTML fragment or ID of the node, second parameter is the reference node where the node will be inserted and the third parameter is position of the relative to the node passed in the second parameter. If the third parameter is not passed, it assumes the default value as “last”.
  2. domConstruct.place takes the third parameter which helps to position the node. The valid values for the third parameter is “before”, “after”, “replace”, “only”, “first”, or “last”. This parameter is optional, so the default value is “last”.
  3. If you pass the third parameter for domConstruct.place is “replace”, the existing node will be replaced with the new node.
  4. domConstruct.create is used for creating the new nodes, then set the attributes and add to the DOM tree. This can be used with existing nodes when you have to assign new attributes. This method takes the four parameters.
    1. tag : A string of the element to create (e.g.: “div”, “a”, “p”, “li”, “script”, “br”), or an existing DOM node to process.
    2. attributes : Object-hash attributes for the newly created element
    3. reference node : This is similar to the refNode attribute in the place method to position this new node.
    4. position : Position of the new node with relative to the third parameter.
  5. domAttr.set is used for setting the attributes to the node. It takes three parameters. First one is node reference, second one is attribute name and third parameter is the value of that attribute.

The above section explains the example code provided in this article. Apart for the methods provided above, there are many other less frequently used methods are empty and destroy. With the use of domConstruct, developers can freely update the DOM tree dynamically. I hope this article is very useful to understand the basic idea behind this API. If you run the above example code, you would get the below output screen.

domconstruct dojo

Filed Under: DOJO Tagged With: dojotoolkit

Search DOM Tree using dojo.query

October 8, 2013 by Krishna Srinivasan Leave a Comment

When working with DOM, it is always good for the developers to get access to the elements in the DOM tree by using the ID or any other handler. Using ID is the most common way of getting access to the specific element in the DOM structure. We have dom.byId method to get the element object. However, just using the exact ID to match the elements is difficult job for the developers and it takes more time for matching the each ID. Also this method has another drawback, it can not be used for getting the elements with the class names in their element tag.

Dojo offers dojo.query to search the elements in DOM structure. It is most advanced method compare to the traditional method dom.byId. The beauty of this method is that it allows us to search the DOM tree by passing the filtering criteria like element name, etc. in the method parameter. Lets look at the following code:

[code lang=”html”]
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
var dojoConfig = {
baseUrl : "src",
packages : [ {
name : "dojo",
location : "dojo"
}, {
name : "dijit",
location : "dijit"
}, {
name : "dojox",
location : "dojox"
}, {
name : "app",
location : "app"
}, ],
parseOnLoad : true,
async : true
};
</script>
<script src="src/dojo/dojo.js"></script>
<script>
require([ "dojo/query",
"dojo/domReady"],
function(query) {
//1. Matching with ID testDiv1 (everything in the dom)
var val1 = query("#testDiv1");

//2. Matching with all the class one (everything in the dom)
var val2 = query(".one");

//3. Searches for class one inside id testDiv2.
//But searches the entire dom to find the element
var val3 = query("#testDiv1 .one");

//4. Searches for class one inside id testDiv2.
//Restricted to search only this ID.
//Improves performance for larger DOM structure.
var val4 = query(".one",document.getElementById("testDiv1"));

//5. Search using the element name
var val5 = query("a.one");
});
</script>
</head>
<body>
<div id="testDiv1">
<div class="one">testDiv1::One</div>
<div class="two">testDiv1::Two</div>
<div class="three">testDiv1::Three</div>
<div class="four">testDiv1::Four</div>
<div class="five">testDiv1::Five</div>
<div class="six"><a class="one">Link One</a></div>
</div>
<div id="testDiv2">
<div class="one">testDiv2::One</div>
<div class="two">testDiv2::Two</div>
<div class="three">testDiv2::Three</div>
<div class="four">testDiv2::Four</div>
<div class="five">testDiv2::Five</div>
</div>
</body>
</html>
[/code]

I have written the explanation as numbered in the above example. I have given five different syntax for the query method and the explanations are provided below.

  1. Matching the elements with the same ID as specified in the method. Note that query method always returns array of objects for the search operation. It returns the list of elements objects matching the same ID.
  2. As I have mentioned above, the advantage of using dojo.query is to search the elements using its class name. In this example, dojo.query
    method returns all the elements having the class name as “one”. Note that, it will return all the elements in the DOM tree.
  3. query(“#testDiv1 .one”) tells the method to search for the element which has class name as “one” and that should be inside the parent element which contains the id “testDiv1”. To find this element, query method searches the entire DOM tree regardless of the any other restrictions. If the DOM tree is very large, then this syntax would cause performance issues for searching the elements. The page response will be very slow if user operation triggers this method frequently. If the DOM tree is small, then this method is good for finding the elements.
  4. query(“.one”,document.getElementById(“testDiv1”) does the same as above method. But, with improved performance. When you have the second parameter in the query method, it restricts the search operation. Which is booster for the performance if the DOM tree is bigger. When you have only one parameter, this method trying to search the entire tree and returns the results.
  5. If you want to get the element straightaway by passing the element name, this method will work for you. You can use this syntax query(“a.one”) to query the element from the specific element type.

I hope this article have provided basic details on how to use the dojo.query to search the elements in DOM tree. 

Filed Under: DOJO Tagged With: dojotoolkit

How to Pass Parameter in AJAX Request using DOJO?

September 30, 2013 by Krishna Srinivasan Leave a Comment

In my previous article I have explained about the very basic article about accessing file in the server using dojo/request. In this post, I would go further on passing the parameter values to the server and return the response that will be printed on the screen. Even this is not a advanced tutorial on using AJAX calls. It is intended for a beginner to learn how to send a simple parameter values to server and get the response.  For advanced users can skip this article.You may read some good dojo tutorials published in JavaBeat.

DOJO AJAX Call Example Listing 1 – dojoajax.jsp

[java]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
var dojoConfig = {
baseUrl : "src",
packages : [ {
name : "dojo",
location : "dojo"
}, {
name : "dijit",
location : "dijit"
}, {
name : "dojox",
location : "dojox"
}, {
name : "app",
location : "app"
}, ],
parseOnLoad : true,
async : true
};
</script>
<script src="src/dojo/dojo.js"></script>
<script>
require([ "dojo/dom",
"dojo/on",
"dojo/request",
"dojo/dom-form" ],
function(dom, on, request, domForm) {
var form = dom.byId(‘frmNode’);
on(form, "submit", function(evt) {
evt.stopPropagation();
evt.preventDefault();
request.post("server.jsp", {
data : domForm.toObject("frmNode"),
timeout : 2000
}).then(function(response) {
dom.byId(‘msg’).innerHTML = response;
},
function (error){
alert(‘error’);
}
);
});
});
</script>
</head>
<body>
<div id="result">
<div>
<label>Message:</label><span id="msg"></span>
</div>
</div>
<form id="frmNode">
<div>
<label>Username: </label><input type="text" name="username" />
</div>
<div>
<label>Password: </label><input type="password" name="password" />
</div>
<button type="submit">Login</button>
</form>
</body>
</html>
[/java]

DOJO AJAX Call Example Listing 2 – server.jsp

[java]
<%
String user = request.getParameter("username");
String pass = request.getParameter("password");
if (user.equals(pass)){
%>
Success!!
<%
}else{
%>
Fails!!
<%
}
%>

[/java]

First one is the mandatory parameters which takes the URL of the server resource. Compare to the previous example, this one uses the specific HTTP request methods for posting the details to the server. It supports the methods request.get, request.post, request.put and request.del.data attribute takes the key value pairs of values and post to the server.

The above example takes the input from the login screen and upon user clicking the submit button, the values are sent to server.jsp where the values are compared and returns a string value. That value will be printed on the screen. The entire process is through AJAX request. In my next example, I would be moving little advanced with using the handleAs attribute for accepting the different return values. The out on the screen looks like below.

DOJO AJAX

Filed Under: DOJO Tagged With: dojotoolkit

A Simple AJAX Example Using DOJO

September 30, 2013 by Krishna Srinivasan Leave a Comment

In the version 1.8, DOJO toolkit announced a new API dojo/request. This API simplifies the AJAX call to the server. As most of the internet applications are using the multiple AJAX request for displaying the data without re-loading the entire page, it becomes necessary for any UI framework has to support the easy and most powerful AJAX mechanism to handle the client requests. DOJO is just does that with an awesome API which can easily written by any novice programmer.

The beauty of the API is that it looks very simple, but complex things are under the curtain. Which makes the developers don’t feel the pain of writing the complex logic them self, instead DOJO takes care of making the asynchronous calls to the server. This post explains the very very simple example for understanding the new API. Which does nothing more than just making call to the server. It is good for first time programmer to read this article, for advanced users can skip this article.You may read some good dojo tutorials published in JavaBeat.

If you are new to DOJO and looking for the getting started tutorials, please refer dojo tutorials. I assume that reader has the basic knowledge on DOJO and AJAX concepts. Lets jump into the example for running this tutorial. It has one jsp with dojo code for making the call to server and another text file with simple text to be printed on alert message.

DOJO AJAX Call Example Listing 1 – dojoajax.jsp

[java]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
var dojoConfig = {
baseUrl : "src",
packages : [ {
name : "dojo",
location : "dojo"
}, {
name : "dijit",
location : "dijit"
}, {
name : "dojox",
location : "dojox"
}, {
name : "app",
location : "app"
}, ],
parseOnLoad : true,
async : true
};
</script>
<script src="src/dojo/dojo.js"></script>
<script>
require(["dojo/request"],function (request){
request("hello.txt").then(
function (text){
console.log("File Content : " + text);
alert(text);
},
function (error){
console.log("Error Occurred: " + error);
}
);
});
</script>
</head>
<body>

</body>
</html>

[/java]

DOJO AJAX Call Example Listing 2 – hello.txt

[java]
It is a test message!!
[/java]

dojo/request is the new API from DOJO 1.8 to make the AJAX server calls. The above example just shows how to access a text file from the server using dojo/request. As it is very simple, it takes the first parameter as the URL (“hello.txt”) which is in the server  and omits the optional parameters. First parameter in dojo/request is mandatory and other parameters are optional. We will learn about the other parameters in the next tutorial. If the server returns the value, first function will be called, the second function will be called if there is any error. If you have the DOJO SetUp in your system, you can copy these codes and run the example right away!!. If you find any issues, please write it in the comments section.

Filed Under: DOJO Tagged With: dojotoolkit

A Simple DOJO Widget Example

September 26, 2013 by Krishna Srinivasan Leave a Comment

Widgets are user interface components that can be dynamically created and plcaed at suitable locations. DOJO provides great support on wide variety of built in widgets and provision to write the custom widgets. DOJO widgets can be created by extending the _WidgetBase class under the dijit package. “_ “at the beginning of any classes in DOJO implies that, that class needs to be extended by another class for the complete functionality.

Prior to the version 1.8, there is another class dijit/_Widget is used for writing the widgets. _Widget still inherits from the base class _WidgetBase, but this will be phased out from the version 2.0. It is always recommended to use the class _WidgetBase for writing any widgets.

  • How to setup dojo?
  • What is dojoConfig?

One of the important aspect on widgets are callback or life cycle methods initiated at the different phase of invoking a widget. These callback methods are defined in its base class _WidgetBase itself. When custom widgets are extending the base class, it inherits the pre-defined life cycle methods. In technical term, widgets are classes that are created with dojo.declare. All the widgets extend the base class _WidgetBase. The following are the important callback methods in each widget. This article explains the very basic example widget using DOJO. This article is intended for the beginners who are interested in writing their first widget program.

DOJO ToolKit

constructor

This is the familiar concept for most of us. This method would be called when new instance is created. Here you can initialize the variavles, arrays, etc.

postMixInProperties

This method is invoked just before the dom nodes are created.It is the last chance to update the instance variables and initialization of properties before the dom nodes are created.

buildRendering

dijit._Templated provides implementation of this method. In most of the cases, we use the dijit._Templated for template our widget. If we want our own template, that has to be done in this method. In this phase only dom nodes are created and hooked with the events. And it is ready for the rendering. Also the resultant content will be set to this.domNode.

setters

The naming convention of the setters method is _setPropertyNameAttr(property). For example, if your property name is age, then setter method has to be _setAgeAttr(property). This method would take one parameter that is used for passing the value to the widget. In the below example you would understand how the values are set inside the widget.

postCreate

This is one of the important method in the life cycle. Most of the customization for the widget is completed in this method. We can say that this is the place where you write anything which is showing as the widget to the user.

startUp

This method is mainly used for ensuring that all the child widgets are created.

destroy

This is not necessary if you don’t have any special clean up things to do for your widget. Most of the time super class would take care of this job. You can omit this method in most of the cases.

Example DOJO Widget Code Listing : 1 (widget.jsp)

[java]
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link rel="stylesheet" href="src/dijit/themes/claro/claro.css"
media="screen">
</head>
<script>
var dojoConfig = {
baseUrl : "src",
packages : [ {
name : "dojo",
location : "dojo"
}, {
name : "dijit",
location : "dijit"
}, {
name : "dojox",
location : "dojox"
}, {
name : "app",
location : "app"
}, ],
parseOnLoad : true,
async : true
};
</script>
<script src="src/dojo/dojo.js"></script>
<script type="text/javascript">
require([ "app/FirstWidget" ]);
</script>
<body>
<span data-dojo-type="app.FirstWidget"
data-dojo-props="name:’Raja’,age:’30’"></span>
</body>
</html>
[/java]

Example DOJO Widget Code Listing : 2 (FirstWidget.js)

[java]
require([ "dojo/_base/declare",
"dojo/dom-construct",
"dojo/parser",
"dojo/ready",
"dijit/_WidgetBase"],
function (declare, domConstruct, parser, ready, _WidgetBase){
declare ("app.FirstWidget",[_WidgetBase],{
i : 10,
name : ”,
age : 0,
constructor : function(){
this.i = 30;
alert ("Inside Constructor");
},
postMixInProperties : function(){
this.i = 20;
alert ("Inside postMixInProperties");
},
buildRendering : function(){
alert ("Inside buildRendering");
this.domNode = domConstruct.create("button",
{innerHTML: "I am Button!!"});
},
_setNameAttr : function(name){
this.name = name;
},
_setAgeAttr : function(age){
this.age = age;
},
postCreate : function(){
alert("Name : " + this.name);
alert("Age : " + this.age);
},
startUP : function(){
alert ("Inside SatrtUp");
}
});

});
[/java]

In the above example, a JSP page which displays the widget. As you can read from the code, it is very simple to invoke the widget by writing the span blocks. The data-dojo-type is the actual widget type or class which will be loaded. data-dojo-props is used for passing the property list to the widgets.

FirstWidget.js defines the list of callback methods. When you execute this example, all the methods will be invoked in the same order.
_setNameAttr is invoked for setting the property values. You can write each method for one property. buildRendering method creates a button and add into the dom tree. This will be displayed in the screen. domNode contains the final dom tree to be displayed in the screen.

Recommended Books:

  • Learning DOJO
  • JavaScript Pocket Reference
  • Head First jquery

Filed Under: DOJO Tagged With: dojotoolkit

A Simple DOJO Example

September 19, 2013 by Krishna Srinivasan Leave a Comment

This article explains very basic DOJO example for the beginners. It is often quite difficult for the beginners to understand the basic concepts and start writing their first example. Once if they know how to start, it is going to be cake walk for them to learn the advanced concepts in the framework. Though most of the developers who are using DOJO would have hailed from the Java background, for them it is often confusing the syntax of delcaring the classes in Javascript. In fact, DOJO provides the similar approach of object oriented concepts which is used in Java.

Lets look into the core basics on DOJO programming. I have covered few important basic details like dojo build and object store in my previous articles. I would request you to read those articles to get more comprehensive knowledge on DOJO programming.

dojo/_base/declare is the DOJO API for declaring the class object. It is similar to the class keyword in Java. Also it supports multiple inheritance for inheriting from its super classes. I found many of the first time programmers misunderstood the concepts on dojo/_base/declare. In simple terms, it is used for declaring the class.

[java]
declare (ClassName,[InheritedClass1,InheritedClass2],{});
[/java]

It takes three paramters as arguments.

  1. First parameter is class name. The name in which you are delclaring will be registered as its name.
  2. Second parameter is list of super classes. Similar to Java, DOJO classes can inherit the properties from its super classes. It supports the multiple inheritance by allowing multple classes to extend. If you don’t want to inherit any super classes, assign this paramter as null value.
  3. Third parameter is the array of properties. It is nothing but, list of variables and methods. How we define variables and methods inside a Java class, similar way DOJO also supports properties and methods defined inside its class. Not only that, one can define constructor for the class. This will be invoked at the time of creating instance for this class. The syntax:

[java]
constructor: function(str1, str2){}
[/java]

The below sample code is the very simple example for declaring a DOJO class.

[java]
define(["dojo/_base/declare",
"dojo/_base/lang",
"app/TestClass1",
"app/TestClass2",
],
function (declare,lang){
return declare ("app.Sample",[TestClass1,TestClass2],
{
constructor: function(str1, str2){
this.str1 = str1;
this.str2 = str2;
},
test : function(){
alert(this.str1 + " " + this.str2);
}
});
}
);
[/java]

define is Asynchronous Module Definition (AMD) API which is used by DOJO to define the classes. AMD is used for improving the performance by loading the resources efficiently. From the version 1.7, DOJO has stsrted using AMD concepts for their APIs. The values added inside define is list of classes or modules required in the class. It is smiliar to import statement in Java.

app.Sample is the class name declared. Testclass1 and TestClass2 are inherited classes. This will be simply null if there is no inherited classes. After the inherited classes, third argument is the array of properties. First one we have declared in this class is the constructor for the same class. Also we have defined a method test. Note that constructir can be utilized for initializing any startup operations.

HTML Code:

[java]
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link rel="stylesheet" href="src/dijit/themes/claro/claro.css"
media="screen">
</head>
<script>
var dojoConfig = {
baseUrl : "src",
packages : [ {
name : "dojo",
location : "dojo"
}, {
name : "dijit",
location : "dijit"
}, {
name : "dojox",
location : "dojox"
}, {
name : "app",
location : "app"
}, ],
parseOnLoad : true,
async : true
};
</script>
<script src="src/dojo/dojo.js"></script>
<script type="text/javascript">
require([ "app/Sample" ], function(Sample) {
var sample = new Sample("Hello", "World!!");
sample.test();
});
</script>
<body>

</body>
</html>

[/java]

dojoConfig is declared with appropriate values. If you are not familiar with dojoConfig, please read our previous article about dojoConfig. Also read how to setup dojo.

[java]
require([ "app/Sample" ], function(Sample) {
var sample = new Sample("Hello", "World!!");
sample.test();
});
[/java]

The above code is just initiating the class and calls method test. It is very simple to write the DOJO programming if you understand the fundamentals of how the classes are defined and initiated. This article itself an example how easy to create a simple example. I have not included the dependencies for running this example, however, it is easy for you with the given examples to get started with your first DOJO programming. If you find trouble on your way, just send me a comment with your problem details. I will try my best to resolve your problems.

Recommended Books:

  • Learning DOJO
  • JavaScript Pocket Reference
  • Head First jquery

Filed Under: DOJO Tagged With: dojotoolkit

Configuring Dojo With dojoConfig

September 18, 2013 by Krishna Srinivasan Leave a Comment

dojoConfig is an object for storing the global configurations used across a page or an application in DOJO. Before dojo components are loaded by the page, dojoConfig has to be configured to pass the global parameters. It is known as djConfig till the version 1.6. djConfig is deprecated and renamed as dojoConfig from the version 1.7 and djConfig will have backward compatibility till the next version 2.0. This configuration object has to be loaded before we are calling the dojo.js loader. Otherwise, important global configurations will not be assigned to internal objects which will be used across the pages.

It is important to understand that dojoConfig and dojo/_base/config are different. dojoConfig is a simple object stores the array of arrays with key value pairs. Whereas dojo/_base/config is used for reading the dojoConfig values and assigned to the suitable varaibles at the time of bootstrap process.

  • How to setup dojo application?
  • How to create tooltip in DOJO?

DOJO ToolKit

In simple terms, the dojoConfig values are accessed by application using the dojo/_base/config class. This config object can not be changed once loaded. This configurations are unique per instance. It means that a single application could load multiple instances of DOJO. Each instance would have its own set of configurations (Reference) .

There are three ways to configure the dojoConfig for your application.

1. data-dojo-config attribute

This is the simplest way for configuring the dojoConfig. When you import the dojo.js using the script tag, add another attribute data-dojo-config and append
all the paramteres with coma seperated delimeter.This is not suitable if the configurations are very huge.

[java]
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/dojo/1.9/dojo/dojo.js"
data-dojo-config="parseOnLoad: true, isDebug: true"></script>
[/java]

2. Explicitly creating dojoConfig object

This option is most widely used by the developers. Here dojoConfig is just delclared as an object with list of configuration parameters. One important point on using this option is to declare this object before dojo core (dojo.js) is not imported. Otherwise the configuration parameters will not be effected.

[java]
<script type="text/javascript">
var dojoConfig = {
parseOnLoad: true,
isDebug: true,
};
</script>
[/java]

I have provided only the basic configuration parameters here. I will explain the use of each paramters in the future sections.

3. dojoConfig object into the build via the scopeDjConfig parameter

This is very rarely used approach for passing the parameters. When you run the dojo build, the dojoConfig parameters has to be passed using the attribute scopeDjConfig. You need not worry on this approach, the above two approaches are good practice in DOJO.

4. dojoConfig Attributes

1. has

One of the greatest feature introduced in version 1.7 is the “has” pattern for detecting the feature. By passing the value true or false, it disable or enable the functionality.

[java]

<script>
dojoConfig = {
has: {
"dojo-amd-factory-scan": false
}
};
</script>

[/java]

2. baseUrl

This is the base url of DOJO application It will be appended to module identifier when looking for the full path.

[java]
baseUrl: "/js"
[/java]

3. Packages

It is an array of objects which provides package names and location of that package.

[java]
packages: [{
name: "myapp",
location: "/js/myapp"
}]
[/java]

4. map

It allows mapping of different paths.

[java]
map: {
dijit16: {
dojo: "dojo16"
}
}
[/java]

5. async

This value tells the loader if the dojo has to be loaded asynchronously. The valid values are true, false or legacyAsync.

[java]

async: true

[/java]

6. parseOnLoad

If you set true for this attribute, scripts are parsed at the time loading the page. Otherwise, you have to intiate the parse operation by invoking the dojo.parse() method. Best practice is to avoid set the value to true, always invoke it mannualy.

7. deps

An array of resource paths which should load immediately once Dojo has loaded.

There are many other attributes defined in the object. Look at below sample code to understand how to use dojoConfig.

[java]
<script>
dojoConfig = {
has: {
"dojo-firebug": true,
"dojo-debug-messages": true
},
parseOnLoad: false,
packages: [
{
name: "test",
location: "/documentation/tutorials/1.9/dojo_config/test"
}
],
waitSeconds: 10,
map: {
"*": {
ready: "dojo/domReady"
}
},
cacheBust: true
};
</script>

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dojo/dojo.js"></script>

<script>
require(["demo/TestDialog", "dojo/parser", "ready!"], function(TestDialog, parser) {
parser.parse();

});
</script>
[/java]

Recommended Books:

  • Learning DOJO
  • JavaScript Pocket Reference
  • Head First jquery

Filed Under: DOJO Tagged With: dojotoolkit

DOJO – Build And Optimize Your DOJO Project

September 17, 2013 by Krishna Srinivasan Leave a Comment

If you are a Java developer, you must be very familiar with the build scripts and have good understanding on the various build tools like ant, maven, etc. We know that the main purpose of the build is too compile (Read : Java Compiler API) the source code to the executable form and then make the distributable archive file. In Java, source files are compiled to byte codes using the compiler and executed in the Java Runtime Environment (JRE).

Why DOJO Build: OK, then why we we need build tool for JavaScript framework?. Is it compiled?. This would be the first question asked by any Java developer who want to start learning the DOJO / JavaScript build. Let me first clear this basic question before start explaining the build process.

DOJO ToolKit

Server Loading Time: Whenever you have to send a code to the client machines through the network, it takes the bandwidth. If the web page is more complicated with more number of JS, CSS and Images, then it has to be downloaded to the browser which is going to make the user wait till the page is loaded. Also browser can not download all the resources simultaneously. It has the limitation of maximum 4 files can be downloaded simultaneously. It means that browser has to make the repeated HTTP requests to server for
downloading the resources.

Optimise CSS, JS, Images: For the above reasons, it is good idea if we optimise the resources used in our web application. Take an example, we have 10 CSS files for the development, if that can be merged into one file at the time of moving the code to production, that saves 9 extra HTTP requests to the server. It is only one way, there are many other aspects like inline, minification, etc. are part of compressing the resources. Note that, optimization will be done only after completing the development and moving the code to production. DOJO build does exactly same thing, it reads the DOJO library and project specific script files, then optimize it by implementing the concept of minification. This is very important for any DOJO project. Without the build process, performance of the application
will be impacted.

This post explores the DOJO build process with very simple example which would be easy for any beginner to understand without much difficulty. If you have any issues on running the DOJO build, please write it in the comments section with code samples. I will try my best to help you solving the problems.

Create DOJO Project Structure

What is Package?: As a first step, create DOJO project as mentioned in this article. It is always good idea to follow the best practice for creating the project structure. The structure consists of packages and modules. Package is a list of modules. We can say that it is a logical grouping of files. Dijit, dojo and dojox packages are separate packages grouped based on their functionality. When you write your own application, you would create your own package to add your files.

What is Module?: Module is a file and it defines a functionality. The keyword define is used for creating the modules. dojo/_base/declare is an example for a module. This file is part of dojo package.

Create Package Descriptor

The package descriptor file (package.json) gives you information about the current package name, such as the name of the package, information about its dependencies, links to licensing and bug tracking information, etc. This file has to be created for every package and copied to the root of the package.This file has the several attributes, but for the dojo build system, dojoBuild is the important and must have property in all the package descriptors. This property informs the dojo build about the location of profile file. Profile file is explained in the next section. A simple package file looks like:

[java]

{
"name": "app",
"description": "DOJOAPP",
"version": 1.0,
"dojoBuild": "dojoapp.profile.js"
}

[/java]

The last property tells the profile file name. Rest of the properties are only optional.

Create Profile File

This is most important file for helping the dojo build system to inform about how it should process the packages. The packages mentioned in this file only will be taken for the build. In our example, util folder under dojo is not required for the application, we can omit that in the profile file. Profile file is created for the each packages and placed on root folder. Most of the applications would have entire application in single package as root, in that case create one profile for root package.

[java]
var profile = {
basePath: "./",
releaseDir: "../release_js",
hasReport: true,
layerOptimize: "closure",
optimize: "closure",
cssOptimize: "comments",
mini: true,
stripConsole: "warn",
selectorEngine: "lite",

packages:[
{
name: "dojo",
location: "dojo"
},
{
name: "dojox",
location: "dojox"
},
{
name: "dijit",
location: "dijit"
}
]
};[/java]

releaseDir indicate that the resulted output will be copied to the folder name releaseDir.

Create Ant Script To Run DOJO Build

  • How to write ant build?

There are two ways to run the build.

  1. Directly running the build.bat file under dojo’s buildscripts path (DOJO_BASE/util/buildscripts).
  2. Invoke the build through ant script.

We are going to run this example using the second approach. Most of the Java projects would use this option since the build can be integrated to their existing build process itself.

[java]
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="build-dojo" name="DOJOBuild">
<property name="WebContent" value="${basedir}/WebContent" />
<target name="build-dojo" >
<java fork="true" dir="${WebContent}/src/util/buildscripts"
classname="org.mozilla.javascript.tools.shell.Main" maxmemory="1024m" >
<classpath>
<pathelement location="${WebContent}/src/util/shrinksafe/shrinksafe.jar" />
<pathelement location="${WebContent}/src/util/shrinksafe/js.jar" />
<pathelement location="${WebContent}/src/util/closureCompiler/compiler.jar" />
</classpath>
<arg value="../../dojo/dojo.js" />
<arg value="baseUrl=../../dojo" />
<arg value="load=build" />
<arg value="profileFile=../../dojo.profile.js" />
<arg value="action=release" />
<arg value="loader=xdomain" />
</java>
</target>
</project>
[/java]

  • shrinksafe.jar, js.jar and compiler.jar files are added to the classpath for running the DOJO build. These files are come with the dojo library under util package. If you download normal source for the development, then util will not be packaged by default. You have to download the full dojo sdk to get these jar files. Other options in the above script is self explanatory and need not have more explanations.
  • java fork is used for executing any external command from the ant script.
  • org.mozilla.javascript.tools.shell.Main is the main class which is invoked from the build libraries.
  • profileFile attribute is the most important as without profile file, build can not take the source files.

Run The DOJO Build

It is simple as running the normal ant script. If you are working on eclipse, right click and select the “Run As Ant”. If the build is
completed, release_js folder would have created with all the files. Compare the files with the original files, you will notice the difference.

Recommended Books:

  • Learning DOJO
  • JavaScript Pocket Reference
  • Head First jquery

Filed Under: DOJO Tagged With: DOJO

How To Use DOJO Object Store?

September 13, 2013 by Krishna Srinivasan Leave a Comment

In my previous article I have explained about the pie chart, bar chart and how to setup DOJO framework. These examples are written with very basic concepts to make the readers understand how to write a simple application without any dynamic data populated from the external storage. This article is the first step towards taking the readers to learn basics about the working on DOJO application with huge amount of data.

DOJO 1.6 has released a great concept as DOJO Object Stores which is simplest way for storing the data locally and manipulate for the presentation. This is emphasized from the  HTML5 object store API idea. Compare to the complex SQL type queries and storage, it is very simple key value pairs and have simple query methods to access the values stored in the local storage.

DOJO ToolKit

The easiest way to start using the store is to implement dojo/store/Memory. This is simple key,value pairs stored in an array. All the values inside array are considered as an object itself. That is why it is called as object stores. dojo/store/Memory allows browser to store the data in the local memory and use ti for the temporary purpose. In most of the cases, we are tend to use the temporary storage for caching and presenting data based on the user interactions.

[java]

//Creating object store from the array
var employeeStore = new dojo.store.Memory({
data: employees,
idProperty: "name"
});

[/java]

Look at the above code, dojo.store.Memory creates new object with the array employees. It is that simple. Later, employeeStore can be used for retrieving the data from the Memory store.

DOJO Object Store Example

[java]

require(["dojo/store/Memory",
"dojo/ready"],

function (Memory, ready) {
ready(function () {

//Creating array of data set
var employees = [{
name: "Krishna",
topic: "Sales"
}, {
name: "Mohhamad",
topic: "Sales"
}, {
name: "Sanaulla",
topic: "Marketing"
}, {
name: "Raja",
topic: "Marketing"
}];

//Creating object store from the array
var employeeStore = new dojo.store.Memory({
data: employees,
idProperty: "name"
});

//Adding new data to the object store directly
employeeStore.add({
name: "Manisha",
topic: "Advertising"
});

//Query the object store to retrieve data
employeeStore.query({
topic: "Marketing"
}).forEach(function (employee) {
alert(employee.name);
});

//Retrieving from object store as object
obj = employeeStore.get("Krishna");
alert(obj.topic);

//Pu object to store
obj.topic = "Marketing";
employeeStore.put(obj);

//Query it again using sort
employeeStore.query({
topic: "Marketing"
}, {
sort: [{
attribute: "topic",
ascending: false
}]
}).forEach(function (employee) {
alert("Sort: " + employee.name);
});
});
});

[/java]

DOJO Object Store API

DOJO object store defines set of methods for accessing the data inside store and perform any operations using these methods.

  1. get(id) –> This method retrieves the object inside an array be looking up the id
  2. query (query, options) –> This is most widely used API method in the object store.  One of the greatest advantage of using the object store is its flexible query method. One can directly use this method on the object store and use the values inside the store. The second parameter in this method “options” used for filtering the values by passing the predefined filer properties.
  3. put(object, options) –> This method simply adds back the object to the store. It means that existing object, once update is completed, use this method to add the object back to the store. Otherwise changes done on that object will not be reflected in the store.
  4. add(object, options) –> It is simply adding the new object to the store.
  5. remove(id) –> Removing an object from the store using identifier.
  6. getIdentity(object) –> This method used for fetching id by passing the object.
  7. queryEngine(query, options) –> This API can be used for advanced operations using query method.
  8. transaction() –> Starts the transaction.
  9. getChildren(object, options) –> Returns child object.
  10. getMetadata(object) –> Retrieves any additional details about an object.

A simple example of how to use object store’s API can be used for a store. Simply use the store’s instance and invoke the method. In the above example, I have used few of the API methods defined above, in the similar way one can use all the methods. If there is any error throw while trying the above example, please write it in the comments section. I will provide help for anyone who contacts me for learning DOJO.

[java]
employeeStore.query({
topic: "Marketing"
}).forEach(function (employee) {
alert(employee.name);
});
[/java]

With the above syntax, it is easy to filter the data using the query method. It can offers sorting of data by passing another argument. As already mentioned in this article, each value inside array is considered as a object itself.

[java]
obj = employeeStore.get("Krishna");
[/java]

Once object is assigned to a variable, just like that update to new values as mentioned in the above example.Note that the object has to be added back to the store using the method put.Otherwise the changes will not be reflected in the object store.

Demo of the above example code

I hope this article given good insight on the basic concepts on the object store. There is JsonRest object store which is used for storing the data from the server. I would write one more article about that in my next article. In practical, Memory and JsonRest would be used together. Keep register with our website (twitter | facebook)to get the latest articles for free.

Reference:

  • DOJO Store
  • HTML5 Web Storage

Recommended Books:

  • Learning DOJO
  • JavaScript Pocket Reference
  • Head First jquery

Filed Under: DOJO Tagged With: dojotoolkit

  • 1
  • 2
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved