简体   繁体   English

对在JavaScript ECMA2015中导入或创建的模块做出反应

[英]Reacting to a module being imported or created in JavaScript ECMA2015

Suppose that we have a module declared like this. 假设我们有一个这样声明的模块。

import Stuff from "./stuff";
export default {
  things: { a: 1 },
  stuff: Stuff
}

Then we fetch it another module and use as shown below. 然后,我们获取它另一个模块并按如下所示使用。

import Donkey from "./stuff-and-things"
console.log(Donkey.things.a);
console.log(Donkey.stuff.whatever-field);

I'd like to be able to react to the importing of the former into the latter, so that when Donkey will be created (added, incorporated, injected whatever it's called), a function will fire. 我希望能够对将前者导入后者做出反应,以便在创建Donkey (添加,合并,注入其所谓的名称)时,将触发一个函数。

Something like this pseudo-code. 像这样的伪代码。

import Stuff from "./stuff";
export default {
  constructor: function(){ console.log("I'm alive!"); }
  things: { a: 1 },
  stuff: Stuff
}

Is it possible at all? 有可能吗? I've been googlearching for a while now and I find nothing - no suggestions on how to nor denial of it. 我已经进行了一段时间的googlearcharch搜索,但没有发现任何内容-没有关于如何操作或拒绝它的建议。 Possibly, I've been using wrong terms due to the ignorance of the subject. 可能由于主题的无知,我一直使用错误的术语。

There isn't a way to be notified when a module is imported. 导入模块时没有通知的方法。 What you could do I guess is export a function instead. 我想你可以做的是导出一个函数。 Then, in order to be do anything useful with that module, the function has to be called first. 然后,为了对该模块执行任何有用的操作,必须首先调用该函数。

For example: 例如:

// stuff-and-things
import Stuff from "./stuff";

const api = {
  things: { a: 1 },
  stuff: Stuff
};
export default function() {
  console.log("I'm alive!");
  return api;
};

// other
import stuffAndThings from "./stuff-and-things"
const Donkey = stuffAndThings();
console.log(Donkey.things.a);
console.log(Donkey.stuff.whateverField);

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

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