Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dojo.require() without dojo.declare()

I'm quite confused from Dojo's documentation. How can I use dojo.require() without actually using dojo.declare()? The reason I don't want to use dojo.declare() is that it exposes declared class as global variable.

Right now my code looks like this:

HTML file:
dojo.require('module.test');

Module/test.js:
dojo.provide('module.test');
function test() {
    return 'found me';
}

I just can't get Dojo to return test() method anywhere. What's the correct pattern for using dojo.require() without declaring?

like image 886
Jim Avatar asked Jan 20 '23 05:01

Jim


2 Answers

I think you are confusing dojo.provide/dojo.require with dojo.declare. They are completely different concepts.

Things that relate to modules

dojo.provide defines a module.

dojo.require requires that a module be defined before running any code later.

Things that relate to JavaScript classes

dojo.declare is something completely different. It declares a Dojo-style class.

You can have multiple classes in a module, or several modules making up one class. In general, modules !== classes and they are completely unrelated concepts.

like image 139
Stephen Chung Avatar answered Feb 11 '23 20:02

Stephen Chung


dojo.provide defines the code module so that the loader will see it and creates an object from the global namespace by that name. From that point, you can anchor code directly to that global variable, e.g.

Module/test.js:

dojo.provide('module.test');

module.test.myFunc = function() {
    return 'found me';
}

There are various patterns you can use, such as creating a closure and hiding "private" function implementations, exposing them via the global reference you created in dojo.provide:

dojo.provide('module.test');

function(){
    // closure to keep top-level definitions out of the global scope
    var myString = 'found me';

    function privateHelper() {
        return myString;
    }

    module.test.myFunc = function() {
        return privateHelper();
    }
}();

Note that the above simply puts methods directly on an object. Now, there's also dojo.declare, which is often used with dojo.provide to create an object with prototypes and mixins so that you can create instances with the 'new' keyword with some inheritance, even simulating multiple inheritance vai mixins. This sort of OO abstraction is often overused. It does approximate the patterns required by languages like Java, so some folks are used to declaring objects for everything.

Note that as of Dojo 1.5, dojo.declare returns an object and does not necessarily need to declare anything in the global scope.

like image 35
peller Avatar answered Feb 11 '23 18:02

peller