2012-08-16 30 views
39
传递

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

好的,这是设置。我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。控制台注销告诉我“人口统计数字===未定义”是true

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

现在我被卡住了,因为我看不到为什么在complaints.js人口统计变量未定义。任何人都可以发现我错过的东西吗?

回答

56

你有循环依赖。 demographics模块取决于complaintscomplaints取决于demographics。由于每documentation

如果你定义一个循环依赖(一个需要B和B需要一个),然后当b的模块函数被调用这种情况下,它会得到一个未定义的值。

解决方案如果无法删除循环依赖项,则需要在其他按需内异步请求其中一个模块(例如,当视图实例化时,而不是定义视图的模块是执行)。 docs再一次覆盖了这个话题。

+0

啊,正是我所怀疑的,但真的没有想到会发生这种情况(我是一个真正的新手,这AMD/requirejs的东西:)我的行动计划是创建另一个模块,将托管两个代码人口统计和抱怨。这意味着这个新模块将用于调用其他两个文件的代码。感谢您确认我的想法。当我得到时间时会试一试。 – 2012-08-16 19:46:46

26

另一种情况是当您定义模块时意外键入require而不是define,我花了一些时间注意到这一点。

11

我有类似的问题。就我而言,定义模块的时候,我会写:的

define('some_dependency', ... 

代替

define(['some_dependency'], ... 
4

另一个可能的原因是执行模块的接口(AMD,CommonJS的),但忘记任何回报。我刚刚做到了。

0

另一个可能的原因可能在事后看来很明显是模块代码中的错误。就我而言,我试图从一个未定义的变量中获取一个属性。该错误记录在控制台中,但出于某种原因,我没有看到它/将其误认为未定义的模块错误。

-1

我只是遇到的另一个原因是:

define(function() { 
    return {}; 
}()); // <-- notice the '()' typo. 

这个“笔误”导致没有JS错误,这一个,并可以把它混淆找出特别是在与许多潜在的循环依赖关系复杂的应用程序。

当然,原因是“拼写错误”是有效的JS,它简单地调用您定义的函数,从而将其结果传递给define(),而不是按预期方式传递函数。