(RPM) The Dojo concept for Java developers __java

Source: Internet
Author: User
Tags websphere application server

the Dojo concept for Java developers

declaring a class and setting the context Dave Draper, WebSphere Application Server Administrative Console Developer, WSO2 Inc. for the past six years, Dave Draper has been serving as WebSphere Applic Development of the ation Server administrative Console. He is a Sun-certified web Component developer who has extensive experience in web-based tool development.

Introduction: Dojo is becoming more and more popular in web-based applications. Many developers are expert in Java™ programming, but lack experience in JavaScript. Moving from a strongly typed, object-oriented compiler language to a dynamic, weakly typed scripting language, developers need to experience the difficulty of conceptual transitions. This confusion makes it difficult for developers to declare Dojo classes correctly. This article will help tease out this confusion, explain why the context must be set, and how to implement it. Mark this article.

Release Date: November 03, 2008
Level: Intermediate
Other language versions: English
visit 860 times Browse
Recommendation: 0 (Add a comment) Average score (total 2 ratings)

Brief Introduction

If you are a developer with little or no JavaScript experience, you may need to master some of the necessary concepts when contacting Dojo. One of the main problems with Dojo (at the time of this article) is that it is still in its infancy (version 1.0 was released in February 2008), and the available documentation is still very limited. This article will help you understand the connection between Dojo and Java code, allowing you to quickly start and master the Toolbox as you develop your application.

This article does not describe how to obtain the Dojo Toolbox or some of the necessary usage instructions because there is already a large amount of resources available for such information. This article focuses on Web developers who have turned to Dojo from servlet development. Ajax Resource Center

Visit the AJAX Resource Center, a one-stop center for information about AJAX programming models, including many documents, tutorials, forums, blogs, wikis, and news. Any new Ajax information can be found here.

JavaScript Hash

One of the major challenges to be faced is to understand the syntax used when invoking Dojo functions, especially "hash" or JavaScript objects. The hash is represented as a set of properties that use a comma interval, and is enclosed in braces. Listing 1 shows a simple example that declares a hash that contains 6 attributes: A string, an integer, a Boolean value, an undefined attribute, another hash, and a function.
Listing 1. Sample JavaScript Hash

				
var Myhash = {
str_attr: "foo",
int_attr:7,
bool_attr:true,
undefined_attr:null,
      hash_attr: {},
func_attr:function () {}
};			

Note that JavaScript is weakly typed, so although each property is initialized to a value associated with its name, it is still necessary to set the Str_attr property to an integer or Boolean value (or any other type). Use the dot operator to access or set each property in the hash (see Listing 2).
Listing 2. Accessing and setting the hash property

				
Accessing a hash attribute ...
Console.log (myhash.str_attr);

Setting a hash attribute ...
myhash.str_attr = "Bar";

The meaning of the first four attributes of Myhash is self-evident. In fact, hash can have a hash attribute, which is not surprising. (This can be seen as a Java class similar to primitives and objects). This is the last important attribute that needs to be understood.

Functions and Objects

Although there is a Java.reflection.Method class in the Java code, it actually serves only as a wrapper for the method. In JavaScript, this function can be any object that can be set, referenced, and passed as a parameter to another function. In general, as with declaring an anonymous inner class in a Java method call, you also need to declare a new function in a function call.

Another important difference between Java methods and JavaScript functions is that JavaScript functions can run in different contexts. In Java programming, use the This keyword to refer to the current instance of the class that you are using. When used in a JavaScript function, this refers to the context in which the function runs. If not specified, the function will run in the closure that defines it.

In the simplest case, closures can be thought of as arbitrary JavaScript code contained in braces ({}). A function declared inside a JavaScript file can use this to access any variable declared in the body of a file, but a function declared in a hash can only use this to refer to a variable declared within the hash, unless the other context is provided.

Because it is often necessary to use closed functions as arguments to Dojo functions, understanding how to set the context eliminates a lot of debugging work.

The main Dojo function used to specify the context is Dojo.hitch. You may never use Dojo.hitch, but you must understand that it is a key part of dojo, and many functions call it internally.

Listing 3 shows how the context connection works (its output is shown in Figure 1): Define a variable in the global context (globalcontextvariable) and declare another variable in a hash context (enclosedvariable). The function Accessglobalcontext () can successfully access the globalcontextvariable and display its value. However, enclosedfunction () can only access its local variable enclosedvariable (note that the Globalcontextvariable value is displayed as "undefined").  Use Dojo.hitch to connect enclosedfunction () to the global context, so that the globalcontextvariable can be displayed (note that enclosedvariable is now "undefined" because it is not running Declared in the context of the enclosedfunction ().
Listing 3. Closures and contexts

				
var globalcontextvariable = "Foo"; function Accessglobalcontext () {    //This'll successfully output "foo" ...    &
Nbsp;console.log (this.globalcontextvariable);

};
var Myhash = {    enclosedvariable: "Bar",     enclosedfunction:function () {                            //Display Global context variable ...                        

     Console.log (this.globalcontextvariable);                            //Display Enclosed context variable ...                             Console.log (this.enclosedVariable
);                   

    };
Console.log ("Calling Accessglobalcontext () ...");

Accessglobalcontext ();
Console.log ("Calling Myhash.enclosedfunction () ...");

Myhash.enclosedfunction ();
Console.log ("Switch the context using Dojo.hitch ...");
var switchcontext = Dojo.hitch (this, myhash.enclosedfunction);
Switchcontext ();             


Figure 1. How the context connection works

declaring classes techniques for declaring classes Although MyClass is a valid name, it is best to declare names in the form of fully qualified class names, such as Com.ibm.dojo.myClass. This does not mean that the class should be deployed to the file system under the relative path "./com/ibm/dojo/"; it simply reduces the chance of conflict with other class names. Will never appear after the last attribute (comma), because some browsers will ignore it (FireFox), but other browsers (Internet Explorer) will eject it. This rule also applies to the declaration of a hash object.

Why connections are so important. You will experience its importance when declaring a Dojo class or creating your own parts. One of the great features of Dojo is the ability to "connect" objects by using the Dojo.connect function and the built-in PUB/SUB model.

The declaration of a class requires three objects: a unique class name used to extend the function's parent class (and simulate multiple inherited "mixed" classes) to define the hash of all properties and functions

Listing 4 shows the simplest way to declare a class, and listing 5 shows the instantiation of the class.
Listing 4. Basic class declaration

				
Dojo.declare (
"MyClass",
null,
{}
);


Listing 5. Basic Class instantiation
				
var myclassinstance = new MyClass ();

If you want to declare a "real" (that is, useful) Dojo class, be sure to understand the constructor. In Java code, you can support instantiation by declaring multiple overloaded constructors with various signatures. In a Dojo class, you can declare a preamble, a constructor, and a postscript, but in most cases you just need to declare a constructor. Unless you are mixing other classes to simulate multiple inheritance, you do not need to use preamble because it allows you to process the constructor parameter before it is passed to the extended class and the mixed class. PostScript produces the Dojo widget lifecycle method, but it is not useful for standard dojo classes.

It is not necessarily all declared, but to pass all values to an instance of the class, you must declare the constructor function as minimum. If the constructor parameters are to be accessed by other methods of the class, they must be assigned to the declared property. Listing 6 shows a class that assigns only one of the constructor parameters to a class property and tries to reference them in another method.
Listing 6. Assignment constructor Parameters

				
Dojo.declare (     "MyClass",     null,     { & NBSP;      ARG1: "",         constructor: function (Arg1, arg2) {               
           THIS.ARG1 = arg1;                       &NBSP},         mymethod:function () {                     
   Console.log (This.arg1 + "," + this.arg2);
                  }

    });
var myclassinstance = new MyClass ("foo", "Bar");Myclassinstance.mymethod ();             


Figure 2. Results of assignment constructor parameters

Complex Property Rules

Class properties can be initialized at declaration time, but if a property is initialized with a complex object type (such as a hash or an array), the property will resemble a public static variable in a Java class. This means that any instance of the modification will be reflected in all other instances whenever it is updated. To avoid this problem, you should initialize complex properties in the constructor, but you do not need to do this for simple properties such as strings, Boolean values, and so on.
Listing 7. Global Class Properties

				
Dojo.declare (     "MyClass",     null,     { & Nbsp;      globalcomplexarg: {val: "foo"},          localcomplexarg:null,         constructor:function () {                            this.localcomplexarg = {val: "Bar"};                                            

       }     });
Create instances of MyClass A and B ... var a = new MyClass ();

var B = new MyClass (); Output a ' s attributes ... console.log ("A ' s global Val: "+ a.globalcomplexarg.val); 

Console.log ("A ' s local val:" + a.localcomplexarg.val);
Update both of A ' s attributes ...
A.globalcomplexarg.val = "Updatedfoo";

A.localcomplexarg.val = "Updatedbar";
Update B ' s attributes ... console.log ("A ' s global val:" + b.globalcomplexarg.val);
Console.log ("A ' s local val:" + b.localcomplexarg.val);             


Figure 3. Class Properties
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.