使用requireJs的模块中的循环依赖关系 [英] Circular Dependencies in modules using requireJs

查看:142
本文介绍了使用requireJs的模块中的循环依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了修复循环依赖关系,请阅读requireJs文档,
,建议使用 exports 为模块创建一个空对象可立即供其他模块参考。

Reading the requireJs documentation,
in order to fix the Circular Dependencies, is suggested to use exports to create an empty object for the module that is available immediately for reference by other modules.

我尝试使用此代码,但似乎无效。怎么了?

I try this code but it seems to do not work. What is wrong?

PS:

读取看到输出的注释,

尤其是setTimeout调用中的B模块。

P.S.:
read the comments for seeing the output,
especially the B module inside setTimeout call.

// A module
define([
    'b'
], function (b) {
    console.log('B:', b); // B, Object
    var A = {
        boo: 1
    };

    return A;
});







// B module
define([
    'a',
    'exports'
], function (a, exports) {
    console.log('A:', a); // A, undefined (as I was expecting)
    exports.A = function () {
        return a;
    }

    var B = {
        bar: 1
    };

    setTimeout(function () {
        console.log('exports.A', exports.A()); // exports.A undefined 
                                           // I would like to access the A object
                                           // which is defined in A module
    }, 500);

    return B;
});







// main.js

(function () {

    define([
        'a'
    ], function () {
    });
}());


推荐答案

你应该可以使用<的同步版本您的B模块中code> require()访问A模块:

You should be able to use the synchronous version of require() in your B module to access the "A" module:

// B module
define([
    'a',
    'exports'
], function (a, exports) {
    console.log('A:', a); // A, undefined (as I was expecting)
    exports.A = function () {
        return require('a');
    }
    ...
});

这篇关于使用requireJs的模块中的循环依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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