Deep understanding of dijit in amd Mode

Source: Internet
Author: User
Tags dojo toolkit
Deep understanding of dijit in amd Mode
  • Difficulty: Beginner
  • Dojo version: 1.8
  • By Mike Wilcox
  • Translator: Leslie (yurychika [at] gmail.com)
  • Original article: http://www.sitepen.com/blog/2012/11/16/dive-into-dijit-with-amd/

The biggest difference between the dojo toolkit and other JavaScript class libraries is the UI component system dijit of dojo. This is a flexible and comprehensive set of dojo modules (supplemented by the corresponding examples and CSS files ). Dijit can help you create flexible, scalable, and modern components. To learn how to install, configure, and use basic dijit in your web application, please continue to read.

Reference appropriate modules and resources

Dijit includes a series of UI components. It is bound to four supported topics: nihilo, Soria, tundra, and Claro. Each topic includes a series of images and CSS files to control the component appearance. The CSS file must be displayed in every HTML page:

<style type="text/css">    /* dojo.css is a CSS Reset, and is optional.    @import "http://ajax.googleapis.com/ajax/libs/dojo/1.8/dojo/resources/dojo.css";    /* Using the claro theme in this example */    @import "http://ajax.googleapis.com/ajax/libs/dojo/1.8/dijit/themes/claro/claro.css";    /* Note that if you don't specify a minor revision, e.g. 1.8.0 or 1.7.1, the CDN will deliver the latest version */</style>

In the body tag on the page or in the parent node of your component, You need to define the class name based on the topic you want.

<body class="claro">

You can use dijit theme tester to view each topic. You can also define your own themes.

Dojoconfig

There are many options in dojoconifg, but the most important two are async and isdebug. During the development process, you will want to set isdebug to true to obtain the appropriate warning information. The async option is used to tell amd loader to load JavaScript modules in a new and fast way.

dojoConfig = {    isDebug:true,    async:true};

Note:ParseonloadYesDojoconfigBut this usage is no longer recommended. See the followingParser.

Dojoconfig is global and must be loaded before you load dojo. Otherwise, it will be ignored. You can also set configuration to an attribute in the script file. In this case, you will use data-Dojo-config.

<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.8/dojo/dojo.js"    data-dojo-config="isDebug:true, async:true" type="text/javascript"></script>

Now it is time to add a control. A quick test is to add a button on the page to verify that everything is as expected.

<body class="claro">    <button data-dojo-type='dijit/form/Button'>Clicky</button></body>


Dojo/parser

As you can see, the control is not correctly parsed. We need to load the dojo/parser and explicitly tell dojo to parse the control. When will we do this? After the Dom is ready. The amd-based judgment method uses the dojo/domready plug-in. AMD was told that a loaded dependency is a plug-in with an exclamation point, such as Dojo/domready !. Because we don't need dojo to do anything before parsing, we can safely put this code at the bottom of the body.

<body class="claro">    <button data-dojo-type='dijit/form/Button'>Clicky</button>    <script>        require([            'dojo/parser',            'dojo/domReady!'        ], function(parser){            parser.parse(); // tell dojo to check the DOM for widgets        });    </script></body>

The control is parsed under the Claro topic, but there is a warning in the consoleWARNING: Modules being Auto-Required: dijit/form/Button.This warning is triggered because controls are not introduced anywhere. To achieve optimal performance for your application, AMD and dojo require you to explicitly define the modules and dependencies you want to use in the application. Dojo1.8 parser is more tolerant. It is asynchronous and smart enough to find and load unintroduced modules. This is not recommended because it is slower to load modules before you want to parse and render them, however, it can capture errors and tell us if the application is not blocked. Dojo 1.7 only fails and an error message is displayed. Adding dijit/form/button to require references can solve this problem and improve performance.

One of the most notable features of the dijit system is that you can create a dijit control using one or two methods: declarative, HTML Tag and custom attributes; or programmatic, use pure JavaScript. Let's take a look at how to transform a basic select element into a dojo-enhanced control.

Create controls

BasicSelectWidget

<select name="character" id="character">    <option value="">Select a character</option>    <option value="Leonard">Dr. Leonard Leakey Hofstadter</option>    <option value="Sheldon" selected="selected">Dr. Sheldon Lee Cooper</option>    <option value="Rajesh">Dr. Rajesh Ramayan Koothrappali</option>    <option value="Howard">Howard Joel Wolowitz</option></select>

This is static and contains a series of options elements.SelectElement. We know that we want to convert this select element into a dijit/form/filterselect control, so we must require this module.

require([    'dojo/parser',    'dojo/domReady!',    'dijit/form/FilteringSelect'], function(parser, domReady, FilteringSelect){    parser.parse();});

Since the dijit/form/filterselect module is available and parser is looking for controls in the Dom, we can use declarative or programmatic methods to enhance our select element.

Declaration Method

The declarative method to enhance the select element is completed in the HTML element itself.

<select name="character" id="characterNode"    data-dojo-type="dijit.form.FilteringSelect"    data-dojo-props='autoComplete:true, pageSize:10' >    <option value="">Select a character</option>    <option value="Leonard">Dr. Leonard Leakey Hofstadter</option>    <option value="Sheldon" selected="selected">Dr. Sheldon Lee Cooper</option>    <option value="Rajesh">Dr. Rajesh Ramayan Koothrappali</option>    <option value="Howard">Howard Joel Wolowitz</option></select>

This declarative example illustrates the use of data-Dojo-type to identify which dijit should be used on a given element. When we call parser. parse (), dojo will find this element and instantiate it and initialize the control.

The options of the dijit/form/filteringselect module are also custom attributes. After you enter a value, the control automatically fills in and 10 items are displayed on each page. Like a normal select element, "Sheldon" will be selected initially.

Programming

The method to enhance the select Element Programming is completely completed using JavaScript.

    require([    'dojo/domReady!',    'dijit/form/FilteringSelect'], function(domReady, FilteringSelect){     var filteringSelect = new FilteringSelect({        autoComplete: true,        pageSize: 10    },'characterNode'); });

Note that the dojo/parser is removed from the dependency list, because the programmatic initialization control does not need to load the dojo/parser module. We can use the same method to create another control.

require([    'dojo/domReady!',    'dijit/form/FilteringSelect',    'dijit/form/Textbox',    'dijit/form/Textarea',    'dijit/form/Checkbox',    'dijit/form/RadioButton',], function(domReady, FilteringSelect, Textbox, Textarea, RadioButton){     var filteringSelect = new FilteringSelect({        autoComplete: true,        pageSize: 10    },'characterNode');     var input = new Textbox({/*options*/},'myInputNode');    var textarea = new Textarea({/*options*/},'myTextareaNode');    var mySelect = new FilteringSelect({/*options*/},'mySelectNode');    var date = new DateTextBox({/*options*/},'myDateNode');    var time = new TimeTextBox({/*options*/},'myTimeNode');    var checkbox = new CheckBox({/*options*/},'myCheckboxNode');    var radio1 = new RadioButton({/*options*/},'myRadio1Node');    var radio2 = new RadioButton({/*options*/},'myRadio2Node');});

If you have a huge form and do not want to add all the independent elements to the dijit control, you can create your own mini parser to create dijits through the selector.

require([    'dojo/domReady!',    'dojo/query',    'dijit/form/FilteringSelect',    'dijit/form/Button',    'dijit/form/CheckBox',    'dijit/form/RadioButton'], function(domReady, query, FilteringSelect, Button, CheckBox, RadioButton){     query('button,select,input').forEach(function(node){        var type = node.nodeName;        if(type === 'INPUT'){            type = node.type.toUpperCase();        }        switch(type){            case 'BUTTON':                new Button({},node); break;            case 'SELECT':                new FilteringSelect({},node); break;            case 'RADIO':                new RadioButton({},node); break;            case 'CHECKBOX':                new CheckBox({},node); break;        }    });});

Of course, this simple example does not convert node attributes into variables and provide them to controls, nor is it any special function of dojo/parser.

Access dijit attributes

You can use the dojo/DOM. byid method to access a specific Dom element. Dijit has its own dijit/Registry. byid method to obtain the dijit control with the registered ID. If the dijit control has an ID, the Control ID is the same value. If an element does not have an id attribute, a control ID is automatically generated. If we want to obtain the "characternode" dijit Control created in the declaration method above, we can use the following code:

require([    'dojo/domReady!',    'dojo/parser',    'dijit/registry',    'dijit/form/FilteringSelect'], function(domReady, parser, registry, FilteringSelect){    parser.parse();    var filteringSelect = registry.byId('characterNode');    console.log('filteringSelect', filteringSelect);});

Use Registry. byid in firebug to view all dijit methods and attributes.

If we want to access the pagesize attribute, we can use dijit getter to access:

var pageSize = registry.byId('characterNode').get('pageSize'); // returns 10

To change the value of pagesize, use the following code:

registry.byId('characterNode').set('pageSize',20); //now pageSize is 20

Note: dojo 1.5 introduces the "get" and "set" methods to process attributes. In dojo 1.4 or earlier, you can use "ATTR" where get and set are used in the previous example ".

Monitor control events

The dijit control uses the dojo/on method to listen to DOM events on a given control:

filteringSelect.on('change', function(value){    console.log('value', value);});

Each control supports a series of events, so please carefully check the documentation to ensure that the events you want to listen to are supported.

It is important to note that they are DOM events. If you want to listen to the widget method, you should use dojo/aspect:

require([    'dojo/aspect'    // other deps...], function(aspect){    aspect.after(filteringSelect, 'validate', function(value){        console.log('validate', value);    });});
Dijit Series

Dijit is also an outstanding UI library, which has the potential to enhance your website and save you a lot of time. Dijit includes many controls, including:

  • Context, pop-up, drop-down menu
  • Form elements, such as buttons, check box, single sheet, and text box
  • Date and Time Selection Control
  • WYSIWYG editor
  • Horizontal and vertical slide bars
  • Progress bar
  • Tab and accordions
  • Tree Structure (including drag and drop)
  • Dialog Box and prompt
  • Layout Control

And if dijit does not have the control you need, it is likely to have it in dojox (Dojo extensions! To view the various controls mentioned above, visit the dojo theme tester.

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.