javascript - 通过 Requirejs 传递的 undefined object

标签 javascript requirejs

我正在使用 Requirejs 在我们的网络应用程序中加载 JavaScript。问题是我得到一个 undefined 对象被传递给一个模块,当在其他模块中使用时,它被实例化得很好。

好的,这是设置。我的 main.js 文件在启动时运行 requirejs:

require.config({
    baseUrl: "/scripts",
    paths: {
        demographics: "Demographics/demographics",
        complaints: "Complaints/complaints",
    }
});

require(["templates", "demographics", "complaints", "crossDomain"], function (templates, demographics, complaints) {
    "use strict";

    console.log("0");
    console.log(demographics === undefined);

    demographics.View.display();
});

在这个问题中,很多配置都被剥离到核心文件。

这是 Demographics.js:

define(["ko", "templates", "complaints", "globals", "underscore"], function (ko, templates, complaints, globals) {

    // Stuff removed.
    return {
        View: view
    };
});

Complaints.js

define([
    "demographics",
    "ko",
    "templates",
    "complaints",
    "visualeffects",
    "globals",
    "webservice",
    "underscore",
    "typewatcher",
    "imagesloaded"],
    function (demographics, ko, templates, complaints, visualeffects, globals, webservice) {
        "use strict";


        console.log("1");
        console.log(demographics === undefined);
    return {
        View: view
    };
});

问题是这样的 - 在 Complaints.js 中,通过 define 配置传递的 demographics 参数是 undefined .控制台注销告诉我“demographics === undefined”是 true

但是,当 main.js 文件执行时,传递给它的 demographics 参数不是未定义的,正如预期的那样,它是一个实例化对象。

现在我卡住了,因为我看不出为什么在 complaints.js 中人口统计变量未定义。任何人都可以发现我遗漏了什么吗?

最佳答案

你有一个循环依赖。 demographics 模块依赖于 complaintscomplaints 依赖于 demographics。根据 documentation :

If you define a circular dependency (a needs b and b needs a), then in this case when b's module function is called, it will get an undefined value for a.

如果您不能消除循环依赖,解决方案是根据需要在另一个模块中异步要求两个模块之一(比如在实例化 View 时而不是在执行定义 View 的模块时)。同样,docs很好地涵盖了这个主题。

关于javascript - 通过 Requirejs 传递的 undefined object ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11991218/

相关文章:

javascript - 使用局部变量从另一个函数停止 setTime

javascript - RequireJS + NodeJS 返回 XMLHttpRequest 无法加载 'http' 没有 'Access-Control-Allow-Origin' header

javascript - 仅实现 FormulaJS 客户端?

javascript - 在没有位置 :absolute 的情况下缩放不相对于其父级的 float div

JavaScript 单选按钮和显示

javascript - 如何在 Angular bootstrap-slider 中单击按钮时获取所选值?

javascript - require.js 未捕获类型错误 : Property '$' of object #<Object> is not a function

javascript - 创建 Web 小部件时,我应该使用容器 div 上的数据属性还是应该向脚本添加参数?

javascript - 如何使用 RequireJS 销毁加载的 Javascript 文件

javascript - 在javascript中创建的div结构与实际的DOM不同