Is it a good practice to give "id" for a dojo widget?

198 views Asked by At

I'm using dojo 1.9 for my projects. I have been following an approach where I give "id" fo each dijits that I use. For ex:

var cp = new dijit.layout.ContentPane({\
 id:"myContentPane",
content:"Test"
});

is it a good practice to assign an id? Reason I do For ex, if I want to reload the cp with a new content, I check to see (by id) if the cp is already created or not. If yes, I just set the content and if not I create it. So above code gets changed to

if(!dijit.byId("myContentPane"){
var cp = new dijit.layout.ContentPane({\
 id:"myContentPane",
content:"Test"
});
}else{
dijit.byId("myContentPane").set("content","new content");
}

so I use id to check if the dijit is already created or not. Very rarely, I use the id to destroy the dijit.

Regards, Manju

2

There are 2 answers

2
GibboK On

I think it is always a good idea to identify your widgets by an unique a reason is:

  • You can retrieve your widget using dijit/registry in a easy and concise way without querying the DOM.

Example of usage:

require(["dijit/registry"], function(registry){
    var widget = registry.byNode(domNode);
});
2
ben On

That is a very personal choice.
However, by experience, on complex single page applications made of of multiple independent dojo modules IDs are very brittle.
On the project I am working, I completely banned them and instead I rely on attachpoints, class properties and widget api.

In your exemple, I assume the var cp = new dijit.layout.ContentPane({ to be in a widget. So I would do:

_setContentAttr: function(content) { if(!this._contentPane) { this._contentPane = new dijit.layout.ContentPane({content: content}); } else { this._contentPane.set('content', content); } }

This way I never rely on ID.

Conclusion is: it depends on your project and its complexity.

  • On simple projects, yeah why not using IDs.
  • On complex one, it's getting brittle and you'd better not.

BTW, as Dojo 1.9 use AMD, you should also avoid using "dijit.layout.ContentPane" and rather use the variable:

require(["dijit/layout/ContentPane"], function(ContentPane){ var cp = new ContentPane(); });