Search code examples
javascriptdojostatic-classes

How do I create a static class using DOJO in Javascript


I am trying to create a Utility class in JavaScript and am using the Dojo framework. I can't find anywhere on here about how to properly create a static class within the Dojo framework. I don't want to have to create a new Utility object every time. I would prefer not to use a Singleton either.

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's ID
            clearTextBox: function (elemID) {
                document.getElementById(elemID).value = "";
            }
        });
    });

NOTE: I am using AMD not Legacy code


Solution

  • As alluded to in one of the comments, you don't need a "class" at all to do what you are asking. This is JavaScript, not Java or C# or etc.

    You just need to define a module which returns an object with utility functions.

    define([], function () {
        return {
            clearTextBox: function (id) {
                document.getElementById(id).value = '';
            }
        };
    });
    

    This is a very common practice, even employed by Dojo itself for utility modules such as dojo/_base/array, dojo/_base/lang, and dojo/date.

    This also does not create a new object each time, as each AMD module is only ever loaded once, and its factory function is only ever executed once.

    Dojo is a toolkit, not a framework, and generally never forces you to do something a certain way. Don't get trapped into thinking that every module you ever create needs to be a "class" using declare. Use declare when you need to define a constructor or mixin with inheritance capabilities.