user1894169
user1894169

Reputation: 39

How get already loaded module without callback?

How get already loaded module without callback?

module_name = 'expected_module';
if(require.specified(module_name)) {
  module = require.get('module_name'); //I want to have here get function, but this function is absent in requirejs
  module.destructor();
}

Upvotes: 0

Views: 114

Answers (2)

Louis
Louis

Reputation: 151401

To check whether a module is actually loaded you need to use require.defined not require.specified. require.specified only checks whether the module has been requested at some point. It may not be loaded yet.

Once you've checked with require.defined that the module is loaded, it is safe to just perform a require call with the module name as the first argument. The return value of the call will be the module. For instance:

if (require.defined("foo")) {
    var foo = require("foo");
    // Do stuff with foo...
}

Whereas generally you do need to pass an array of dependencies and a callback to require calls, RequireJS does support calling require like above. However, it will be successful only if the module is already loaded, but we check for that with require.define.

So your code should be modified to:

module_name = 'expected_module';
if(require.defined(module_name)) {
  module = require('module_name');
  module.destructor();
}

Upvotes: 1

Sandeep Nayak
Sandeep Nayak

Reputation: 4757

You can do this:

require(['expected_module'], function(module){

    module.destructor();   //call methods in your module

});

The callback is necessary since require loads all modules and their dependencies async. The code written inside callback executes only when all dependencies are loaded.

Upvotes: 0

Related Questions