Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve circular dependency in Require.js?

Basically, the idea is that "sub" module creates an object, and that object should be part of a utilities library which is the "main" module. However, the "sub" object depends on utilities from "main":

// Main module
define(['sub'], function(sub) {
    var utils = {
        utilityMain: function () {
           // ...
        };
        // ...
    };

    tools.subModule = sub;

    return tools;
});

// Sub module
define(['main'], function(main) {
    return new (function () {

        // Singleton object using functions in main module
        var somestuff = function () {
            main.utilityMain();
            // etc
        };
    })();
});   

How can I achieve this with require.js without creating a black hole that would swallow the whole planet?

Thank you very much.

like image 683
pilau Avatar asked Jun 17 '13 11:06

pilau


1 Answers

There are a few things suggested in the docs:

b can fetch a later after modules have been defined by using the require() method (be sure to specify require as a dependency so the right context is used to look up a)

e.g.:

// Sub module
define(['require'], function(require) {
    return new (function () {

        // Singleton object using functions in main module
        var somestuff = function () {
            require('main').utilityMain();
            // etc
        };
    })();
});

or

you could instead use exports to create an empty object for the module that is available immediately for reference by other modules

e.g.:

// Main module
define(['sub', 'exports'], function(sub, exports) {
    exports.utilityMain: function () {
       // ...
    };

    exports.subModule = sub.sub;
});
// Sub module
define(['main', 'exports'], function(main, exports) {
    exports.sub = new (function () {

        // Singleton object using functions in main module
        var somestuff = function () {
            main.utilityMain();
            // etc
        };
    })();
});

and

Circular dependencies are rare, and usually a sign that you might want to rethink the design

like image 188
freejosh Avatar answered Oct 03 '22 12:10

freejosh