Jeremy Spencer
Jeremy Spencer

Reputation: 250

Dojo data attributes

I've been looking into Dojo lately as an alternative to jQuery and Backbone. I like it so far, but the only thing I dislike is that Dojo uses HTML5 data* attributes.

I don't particularly like mixing Javascript and HTML, I prefer to keep everything completely separate. Is there a way to do this with Dojo?

Upvotes: 0

Views: 1070

Answers (1)

Dimitri Mestdagh
Dimitri Mestdagh

Reputation: 44665

You can either choose if you write your widgets programmatically or declarative. Benefits/differences between both are compared at the links @BuffaloBuffalo gave you.

Declarative

HTML

<button data-dojo-type="dijit/form/Button">Click me</button>

JavaScript

require(["dijit/form/Button", "dojo/parser"]);

You have to put parseOnLoad: true in your Dojo configuration or manually parse the node using the dojo/parser module API.


Programmatically

HTML

<button id="myBtn">Click me</button>

JavaScript

require(["dojo/dom", "dijit/form/Button", "dojo/domReady!"], function(dom, Button) {
    new Button({
        label: "Click me"
    }, dom.byId("myBtn"));
});

The differences are quite clear, but there's one thing to note. As you can see, the declarative code takes the label from the button, this does not happen when using programmatically created widgets. They only use the DOM node as a placeholder, it doesn't look at its properties or HTML attributes.


However, you can do a lot more with data-properties other than defining widget. I'll list them below and give you an alternative to how you could achieve the same thing using JavaScript:

  • data-dojo-config is used to load the Dojo configuration. The alternative to this is by creating a JavaScript file and declaring a dojoConfig global object containing these properties.
  • data-dojo-attach-point and data-dojo-attach-event are used to create attach points or references to the DOM nodes rendered from the template. You can achieve the same thing by using the dojo/query module and obtaining the correct DOM node/event handler by querying your widget domNode
  • data-dojo-props gives you the possibility to configure widget properties through HTML5 attributes. The alternative to it is to obtain a widget reference and using the set() function.

Upvotes: 1

Related Questions