How to create static class using DOJO in Javascript
I am trying to create a Utility class in JavaScript and using the Dojo framework. I can't find anything here on how to properly create a static class within the Dojo framework. I don't want to create a new Utility object every time. I would rather not use Singleton.
I currently have something like this ...
//Util.js
define(["dojo/_base/declare",
"dojo/domReady!"], function (declare) {
return declare(null, {
//Pass in string format of element ID
clearTextBox: function (elemID) {
document.getElementById(elemID).value = "";
}
});
});
NOTE. I am using AMD not Legacy code
source to share
As stated in one of the comments, you don't need a "class" at all to do what you ask. This is JavaScript, not Java or C #, etc.
You just need to define a module that returns an object with useful functions.
define([], function () {
return {
clearTextBox: function (id) {
document.getElementById(id).value = '';
}
};
});
This is a very common practice, even used by Dojo itself for service modules such as dojo/_base/array
, dojo/_base/lang
and dojo/date
.
It also doesn't create a new object every time, as each AMD module is loaded only once, and its factory function is only executed once.
Dojo is a toolbox, not a framework, and generally never forces you to do something in a particular way. Don't get carried away with the idea that every module you've ever created must be a "class" using declare
. Use declare
when you need to define a constructor or mixin with inheritance capabilities.
source to share