繁体   English   中英

requirejs加载相同的模块两次

[英]requirejs loading same module twice

我正在使用https://github.com/volojs/create-template中的单页应用模板

我试着在下面做一个简单的例子。

问题

ModuleA.js被加载两次,一次是直接来自main.jsmain.js一次来自simulator.js ,这也取决于该模块。 这导致对一个对象的两个不同的引用(我认为它只是一个,像一个单例)。 我以为requirejs不会加载相同的模块两次。 作为(相对)新的JavaScript,我意识到这对我来说可能是天真的。 我正在尝试按照模板。

这是一个演示问题的简化版本:

WWW / index.html的

<head>
...
    <script data-main="app" src="lib/require.js"></script>
</head>
...

WWW / app.js

// For any third party dependencies, like jQuery, place them in the lib folder.
// Configure loading modules from the lib directory,
// except for 'app' ones, which are in a sibling
// directory.

requirejs.config({
    baseUrl: 'lib',
    paths: {
        app: '../app'
    }
});

// Start loading the main app file. Put all of
// your application logic in there.
requirejs(['app/main']);

WWW /应用程序/ main.js

define(function (require) {
    var simulator = require('./simulator.js');
    var ModuleA = require('./ModuleA.js');

    ModuleA.init();
    ModuleA.displayList();
    ModuleA.update("joe", 99);
    ModuleA.displayList();

    simulator.start(); // should display the same list
});

WWW /应用程序/ ModuleA.js

define(function () {
    var theList = {};
    console.log("loading ModuleA");
    return {
        displayList: function () {
            console.log(Object.keys(theList));
        },
        init : function () {
            theList["fred"] = 10;
        },
        update : function (k, v) {
            theList[k] = v;
        }
    }
});

WWW /应用程序/ simulator.js

define(["./ModuleA"], function (ModuleA) {
  return {
    start: function () {
      ModuleA.displayList();
    }
  };
});

控制台输出:

loading ModuleA
loading ModuleA
["fred"]
["fred", "joe"]
[]

由于第二次加载ModuleA ,最后一行显示的空[]可能是列表的第二个副本。

问题是模块引用不一致。 在main.js中它需要./ModuleA.js而在simulator.js中它定义./ModuleA (没有.js文件类型)。

使这些引用相同可以纠正行为,使模块仅加载一次。

我想我混合了样式,因为网上有很多例子。 它看起来像一个错误,它以这种方式工作,但也许这是一个功能?

如果要使用requireJS共享实例化的单例对象,可以为ModuleA执行以下操作:

define(function () {
  console.log("loading ModuleA");
  function myList(){
    this.theList = {}
  } 
  myList.prototype.displayList = function () { 
      console.log(Object.keys(this.theList));
  } 
  myList.prototype.init = function () { 
      this.theList["fred"] = 10;
  } 
  myList.prototype.update = function (k, v) { 
      this.theList[k] = v;
  } 
  return new myList();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM