Dojo 1.6 official Tutorial: create a custom dojo widget)

Source: Internet
Author: User
Document directory
  • The first step is to create the necessary directory structure for the custom widget
  • Step 2: Create an HTML clip to display a single author
  • Step 3: convert HTML fragments into dijit templates
  • Step 4: Use dojo. Declare to create a widget class
  • Step 5: beautify

In this tutorial, we will demonstrate how to use the dojo and dijit frameworks to create custom widgets. Dijit. _ widget and dijit. _ templated base classes and Mixin are mainly used.
For basic dijit framework knowledge, see the first two tutorials.

Difficulty: Moderate
Applicable dojo version: 1.6

By Brian Arnold
Brian Arnold is a software engineer at sitepen, Inc. he has a lovely wife, two cute dogs, is an active member of (and presenter at) webuquerque, and ranks among the top 3% of fake guitarists in rock band.
Connection: http://dojotoolkit.org/documentation/tutorials/1.6/recipes/custom_widget/

Feijia tiimfei@gmail.com

The dijit library of dojo contains a variety of interface widgets (widgets). By using these widgets, you can create a powerful web application interface, from advanced form elements, to the complex page layout.

However, for some complex applications, developers will still encounter further customization requirements, such as complicated information presentation requirements. Of course, you can manually construct the Dom to display data, but if you use the frameworks and tools provided by dijit, we can quickly develop flexible and powerful custom widgets.

Scenario

Suppose we need to develop a page that shows the introduction information of all the author of the dojo tutorial. The data source at hand is the following JSON data:

[    {        "name": "Brian Arnold",        "avatar": "/includes/authors/brian_arnold/avatar.jpg",        "bio": "Brian Arnold is a software engineer at SitePen, Inc., ..."    },    /* More authors here... */]

We need to display the following Dom structure on the page:

<body>    <!-- Headers and whatnot -->    

Of course, we hope that this display page can be used with some more effects. For example, when you move the mouse over an author, the background color can fade into the display.

The page effect is as follows:

Solution

We can create a custom dojo widget to implement this requirement. The steps are as follows:

1. Create the necessary widget directory structure
2. Create HTML tags for displaying a single author
3. convert these tags into dijit templates based on #2.
4. Use dojo. Declare to create our widget class
5. Make necessary CSS beautification

The first step is to create the necessary directory structure for the custom widget

Although this step seems redundant, it is a good programming habit to arrange a reasonable directory structure for your custom widgets. Here I will create a directory named custom as the namespace for storing all my code and templates. Of course, the directory name depends entirely on you. It can be the name of the institution you work. Then I name the custom widget to be created as authorwidget, so I will create an authorwidget directory that contains the CSS and HTML templates and Source Code related to the widget. The final file structure is shown in:

Step 2: Create an HTML clip to display a single author

As the first custom widget, we will try to start with the simplest one. It only displays some data on the page.

Here we use the following simple snippet to show the information of an author. The outermost layer is a container Div. Remember to create a dijit template with a unique root node. Here, the container div is the root node of our template. Then we use an H3 label to show the author's name, an IMG label to show the Avatar, and a p label to show the author's introduction.

<div>    

Step 3: convert HTML fragments into dijit templates

When dijit. _ templated (the base class of our widget) is used, you can perform many operations on the template:

1. You can automatically Insert variable values in the template.
2. You define attach point in the template by yourself, So that you reference and program to manipulate these DOM elements in the widget
3. You can set DOM event processing functions on the elements in the template.

In our example, we mainly use automatic variable value insertion. Now let's create a file: custom/authorwidget/templates/authorwidget.html. The content of the file is basically similar to the HTML segment in step 2, but some dijit template-specific attributes will be added.

<div>    

In this template:

1. We use the $ {attribute} syntax to insert some values directly. For example, we have inserted the author name $ {name}

2. Similarly, there is another Syntax: $ {! Attribute}. The difference between the two is: $ {! Attribute} inserts the value as is without escaping. Here we are at $ {! Bio} position value to be replaced will contain some HTML tags, we do not want dijit. _ templated to escape these tags.

3. All widgets Based on dijit. _ widgets have a baseclass attribute.

4. In the above template, I have defined the attachment point attribute for each node, so that Code such as myauthor. namenode can be directly used in my code to access the H3 node.

You may have noticed that the src attribute value is not specified in the IMG tag of the template. What if an author in our data does not contain an avatar image? We need to be able to automatically set the default values to handle such situations when creating our widgets. The subsequent steps will further explain how to solve this problem.

Step 4: Use dojo. Declare to create a widget class

In this step, create authorwidget. js in the Custom directory. In addition, we add an image file with the default avatar.

The Created directory and file structure are as follows:

In authorwidget. JS, we will use dojo. Declare to create our widget class. As follows:

// Custom. authorwidgetdojo. provide ("custom. authorwidget "); // declare the dependent module and base class dojo. require ("dijit. _ widget "); dojo. require ("dijit. _ templated "); // create our widget! Dojo. declare ("custom. authorwidget ", [dijit. _ widget, dijit. _ templated], {/* our custom widget attributes will be added here */}) // and that's it!

In this Code:

1. We use dojo. Provide to declare that our JS file provides a resource named custom. authorwidget. Since 1.6, dojo has added support for asynchronous module loading mechanism (AMD). However, for simplicity, we use the traditional dojo module declaration and Loading System (Dojo. provide and dojo. require ).

2. We used dojo. require to reference the modules that our widgets depend on (dijit. _ widget and dijit. _ templated)

3. We use dojo. Declare to declare a class, custom. authorwidget, which uses dijit. _ widget and dijit. _ templated as the base class.

Note that in this JS file, we do not need to use dojo. Ready ---- This is because we are developing a dojo module. The module Loading System of dojo ensures that all the modules you depend on are loaded successfully before running and loading subsequent modules.

Of course, the above Code is just an empty shelf. To make it really work, we also need to set a series of attributes for our widgets. The following is the code snippet of dojo. Declare with the property settings added.

Dojo. declare ("custom. authorwidget ", [dijit. _ widget, dijit. _ templated], {// set some default values // These typically map to whatever you're handing into the constructor name: "No Name", // using dojo. moduleurl, we can get a path to our authorwidget's space // and we want to have a default avatar, Just in case Avatar: dojo. moduleurl ("custom. authorwidget "," images/defaultavatar.png "), Bio:" ", // load our template-importa NT! Templatestring: dojo. cache ("custom. authorwidget "," templates/authorwidget.html "), // the CSS class name baseclass:" authorwidget ", // reference to our background animation object mouseanim: NULL, // The color attribute basebackgroundcolor: "# fff", mousebackgroundcolor: "# Def "});

First, we define some attributes for saving the author's basic information: name, description, and Avatar. We also provide default values for these attributes. When setting the default value of the Avatar, we use dojo. moduleurl to reference the path of the current widget and access the image folder under this path.

By using the templatestring attribute and dojo. cache, we loaded the previously defined template file.

Set the baseclass attribute to the CSS class of the DOM root node of the widget. Here is the outermost Div node in our template.

We also set the attributes used to set the animation attributes and the background color.

So far, our widget has taken shape. In fact, it can run and display some simple information. Of course, we need to further improve it.

Next we will add the postcreate method, a custom avatar setting method, and an auxiliary method to change the background color.

The postcreate method is the main entry for adding our work logic. Its call time is after the DOM structure of the widget is successfully created, but it is not added to the DOM tree of the page (that is, the user cannot see the DOM node of the widget ). Therefore, we usually put the initialization work in this method.

postCreate: function(){    // Get a DOM node reference for the root of our widget    var domNode = this.domNode;     // Run any parent postCreate processes - can be done at any point    this.inherited(arguments);     // Set our DOM node's background color to white -    // smoothes out the mouseenter/leave event animations    dojo.style(domNode, "backgroundColor", this.baseBackgroundColor);    // Set up our mouseenter/leave events - using dijit._Widget's connect    // means that our callback will execute with `this` set to our widget    this.connect(domNode, "onmouseenter", function(e) {        this._changeBackground(this.mouseBackgroundColor);    });    this.connect(domNode, "onmouseleave", function(e) {        this._changeBackground(this.baseBackgroundColor);    });}

In postcreate, we use the basebackgroundcolor attribute to set the domnode background color and the onmouseenter and onmouseleave event processing functions. Therefore, when you hover your mouse over our Dom node, the _ changebackground function is called. Let's take a look at this function:

_changeBackground: function(toCol) {    // If we have an animation, stop it    if (this.mouseAnim) { this.mouseAnim.stop(); }     // Set up the new animation    this.mouseAnim = dojo.animateProperty({        node: this.domNode,        properties: {            backgroundColor: toCol        },        onEnd: dojo.hitch(this, function() {            // Clean up our mouseAnim property            this.mouseAnim = null;        })    }).play();}

Note: Why do we need to underline the method name? This is a dojo naming convention. The method or object is an internal member of the class and should not be directly used by the user by an underscore before the method and object attribute. Although the Javascript language does not forcibly prohibit such calls, this is a good programming habit and a method to prompt users to use the API correctly.

In this method, we first check whether an animation is currently being executed, and if so, stop it first. Then, set a new animation, save it in mouseanim, and start playing. This example is very similar to our effect in the http://dojotoolkit.org/documentation/tutorials/1.6/animation/ of the dojo animation tutorial, but the color is different.

Finally, we need to solve the problem: if an author does not provide an avatar image, we need to set a default Avatar for it. Here we create a custom property setting method (custom setter. These methods have fixed naming rules. _ setxxxattr, where XXX is the name of the attribute you want to set (the first letter must be capitalized ). For example, we want to set the "avatar attribute" here. Therefore, the required method name is _ setavatarattr.

When a widget is created or you use the property setting method mywidget. Set ("Avatar", somepath), the custom property method is called.

_setAvatarAttr: function(av) {    // We only want to set it if it's a non-empty string    if (av != "") {        // Save it on our widget instance - note that        // we're using _set, to support anyone using        // our widget's Watch functionality, to watch values change        this._set("avatar", av);         // Using our avatarNode attach point, set its src value        this.avatarNode.src = av;    }}

This method is mainly used to perform a security check. When a user passes in an empty string, the default avatar is used.

From dojo1.6, all widgets Based on dijit. _ widgets will automatically inherit the dojo. stateful class, which is added to the monitoring of class attribute changes. We use the this. _ set () method in _ setavatarattr to follow the dojo. stateful rules and ensure that all attribute changes can be detected.

After all this is done, we now have a working widget. Although it does not look so beautiful.

View examples

Step 5: beautify

One of the advantages of using dijit. _ widgets is that it provides a baseclass attribute as the CSS style class of the root node. The Created directory structure contains a special CSS directory. Next, we create an authorwidget.css file in the cssdirectory.

/* AuthorWidget.css */.authorWidget {    border: 1px solid black;    width: 400px;    padding: 10px;    overflow: hidden; /* I hear this helps clear floats inside */} .authorWidget h3 {    font-size: 1.5em;    font-style: italic;    text-align: center;    margin: 0px;} .authorWidgetAvatar {    float: left;    margin: 4px 12px 6px 0px;    max-width: 75px;    max-height: 75px;}

We can see that the authorwidget class is defined by baseclass and will be applied to the DIV root node of the template. At the same time, the template also contains the $ {baseclass} Avatar class, so we define the authorwidgetavatar class. (This is just some of the most basic beautification. Don't ask me too much. I am not a designer)

The last step is to add our CSS file to the header of the page, so we have a beautiful author list widget!

View examples

Summary

In this tutorial, we can see that dijit. _ widget and dijit. _ templated are used as the base class. It is very easy to create a custom widget. We can quickly create templates, add custom logic, and define our own CSS to beautify the appearance of widgets.

Although this example is very simple, you need to know that the vast majority of dijit widgets are developed based on these two basic classes. Using these tools, you can develop powerful interface components. The reference below lists some good documents for your reference.

* Dijit. _ widget on the dojo Reference Guide
* Dijit. _ templated on the dojo Reference Guide
* Tutorial on dojo. Declare
* Dojo Reference Guide: writing your own widget

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.