Luis Crespo
Luis Crespo

Reputation: 788

Does Dojo AMD loader ensure modules are executed only once?

In some existing Dojo-based app I am seeing a module using a singleton pattern of the form:

define([...], function(...) {
  var MyClass = declare(...);
  if (!_instance) {
    var _instance = new MyClass();
  }
  return _instance;
});

But if I understand AMD correctly, the usage of _instance is not required, because the function passed to the define(...) call should be executed only once... or maybe not?

My understanding of the AMD loader is that when getting a module by calling "require" or "define", it will check whether the module has already been loaded. If it has not been loaded yet, it will load the JS, execute the function passed to "define", and internally store the returned value. If it has already been loaded, it will simply return the previously-stored value.

Are my assumptions correct? If so, when writing a module, we can safely assume that a given module will only be loaded and executed once, and we don't need to perform any check to see whether something has already been initialized or not, making the code simpler.

Thank you.

Upvotes: 4

Views: 308

Answers (1)

Marius
Marius

Reputation: 423

You are right i a way, but not entirely

define("my.widget", [ "dojo/_base/declare",.... ], function(declare, ...){
    return declare("my.widget", [ .. ], {
        value : "myvalue"
    });
});

here we define module which defines class, so class declaration(constructor) is cached when module is required, meaning class is defined only once. But that doesn't mean you can use it as static, because that's only class declaration, not the instance.

this will not work:

require(["my.widget"], function(widget) {
    console.log(widget.value);
});

Here is correct usage:

require(["my.widget"], function(widget) {
    console.log(new widget().value);
});

Upvotes: 3

Related Questions