JavaScript ES6模块OnLoad处理程序实现

我有一个NodeJS服务器应用程序被分割成ES6模块丢失。 我正在尝试创build一种“加载模块处理程序”,这是主模块中的一个函数,其他模块需要注册一个callback函数,在主模块完全初始化后执行。 我使用Babel(带有babel-preset-es2015 )将ES6模块转换为可执行的JavaScript。

为了演示这个问题简而言之,我创build了2个示例文件。

文件index.js (应用程序条目,主要模块):

 import * as js2 from "./js2.js"; let toCall = [], // this array handles callbacks from other modules initialized = false; // flag export function onInit (cb) { // registers cb to execute after this module is initialized if (initialized) { cb(); return; } toCall.push(cb); } function done () { // initialization is done - execute all registered callbacks toCall.forEach(f => f()); } // some important stuff here // callback(() => { initialized = true; done(); // }); 

而另一个模块js2.js

 import { onInit } from "./index"; onInit(() => { console.log("Now I can use initialized application!"); }); 

对我来说似乎都可以,但不幸的是,这并不能在第一个文件中抛出下一个错误:

 Cannot read property 'push' of undefined 

事情是,在这一点上没有toCallvariables,但为什么呢? variablestoCall onInit函数之前 onInit ,它必须准备在onInit使用,不是吗? 如何解决这个问题,是我的方式足够合理的实现一个叫做“模块初始化callback”的东西? 有没有其他解决scheme呢?

感谢您的任何帮助和build议。

我发现了一个漂亮的实现。

需要将“onload handler”实现分离到单个模块。 作为这个例子的结果,将会有三个文件:

index.js

 import * as js2 from "./js2.js"; import { initDone } from "./init.js"; // some important stuff here // callback(() => { console.log(`Main module is initialized!`); initDone(); // }); 

js2.js

 import { onInit } from "./init.js"; onInit(() => { console.log("Module js2.js is initialized!"); }); 

init.js

 let toCall = [], // this array has to handle functions from other modules initialized = false; // init flag export function onInit (cb) { if (initialized) { cb(); return; } toCall.push(cb); } export function initDone () { initialized = true; toCall.forEach(f => f()); } 

结果是:

 Main module is initialized! Module js2.js is initialized!