Dojo FAQ: What does Dojo’s parser do?

By on April 16, 2014 9:53 am


The Dojo Parser provides the ability to declaratively instantiate widgets within our markup, allowing you to add Dojo widgets to your page in the same way you are accustomed to adding HTML5 widgets and form elements, keeping your JavaScript free of boilerplate instantiation code. It does this by scanning the DOM for nodes containing a data-dojo-type attribute and instantiating widgets in place of those nodes. It can scan the page automatically when parseOnLoad is true in our Dojo configuration, or it can be invoked manually by requiring the dojo/parser module and then calling it’s parse method. The parser is also used by Dijit’s _WidgetsInTemplateMixin so we can declaratively instantiate widgets from within our widget templates.

], function (parser) {
    // calling parse with no arguments will scan from the root node

On the surface, Dojo’s parser seems like a pretty simple module, but it can actually be used in a number of advanced ways. If the widget needs additional mixins, they can be provided as a comma-separated list to the data-dojo-mixins attribute. Arguments can be specified in the data-dojo-props attribute to be passed to the widget constructor during instantiation.

Running the parser

The simplest way to run the Dojo Parser is to configure it to load when the page loads by setting parseOnLoad to true in your Dojo configuration. This is useful if your initial page contains declarative widgets. However, the preferred method is to simply call the parser directly. Include dojo/parser as a dependency and then call parser.parse().

<script type="text/javascript">
], function (parser) {

This will scan the entire page for declared widgets and instantiate them. It can be scoped by providing a root node as an argument to the parse call. In version 1.8+ of the toolkit, the parser is intelligent enough to auto-require modules, eliminating the need to specify them in the require call, but it is still advised that you do so, as this will ensure that the dependencies will be included in a layers file during a project build.

Beyond instantiation

The parser also allows for widget behavior to be specified declaratively through the inclusion of custom script tags within the widget declaration. Referred to as declarative scripting, this technique allows us to monitor events, monitor and change properties, and aspect methods of our widget, all within specialized script tags . For example, we can execute code when the value of our widget changes:

While it can be handy, declarative scripting should be used with caution as there may be performance issues and limitations depending on the environment.

The parser is a powerful tool that can be used to make our code easier to read, easier to write, and easier to share!