如何解决 Require.js 中的循环依赖? [英] How to solve circular dependency in Require.js?

查看:40
本文介绍了如何解决 Require.js 中的循环依赖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,这个想法是子"模块创建一个对象,该对象应该是主"模块的实用程序库的一部分.但是,sub"对象依赖来自main"的实用程序:

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
        };
    })();
});   

如何使用 require.js 实现这一目标,同时又不会产生一个可以吞噬整个星球的黑洞?

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

非常感谢.

推荐答案

文档:

b 可以在使用 require() 方法定义模块后稍后获取 a(确保指定 require 作为依赖项所以正确的上下文用于查找 a)

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)

例如:

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

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

您可以改为使用 exports 为模块创建一个空对象,该对象可立即供其他模块引用

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

例如:

// 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
        };
    })();
});

循环依赖很少见,通常表明您可能想要重新考虑设计

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

这篇关于如何解决 Require.js 中的循环依赖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆