javascript - 避免循环依赖:替换事件的导入?
问题描述
我将一个文件代码拆分为多个文件代码,并且遇到了一些循环依赖项。
其中一些,我可以通过重构来避免它们,另一些看起来更复杂,或者对我来说没有意义,因为重构可能意味着必须将大量代码放在同一个文件中,而不是按特性/功能拆分它。
我已经看到其他组件使用事件在模块之间进行通信,我认为我可以使用相同的技术来避免循环依赖,但是....我不确定这是否只是一个丑陋的黑客而不是正确的方法正在做。
因此,例如,具有以下内容:
import { sayHi } from 'introductions.js';
export function demo(){
// stuff here
sayHi(stuff); // circular dependency here
}
我在想我可以将其替换为以下内容:
export function demo(){
// do stuff here
emit('sayHi', stuff); // event here, avoiding the import
}
//introductions.js
import { whatever } from './whatever.js';
on('sayHi', function(stuff){
sayHi(stuff);
});
function sayHi(stuff){
console.log("Hi " + stuff);
}
...
这会是一个适当的解决方案吗?或者只是一个丑陋的黑客来“删除”循环依赖?
解决方案
推荐阅读
- presto - 如何在 Presto 中执行多条语句?
- xamarin.forms - ClassNotFoundException: PowerSaveModeBroadcastReciever
- java - 无法打开应用,因为它来自身份不明的开发者
- python - 如何将分离的部分(来自 k-means 聚类)保存为不同的 Dataframe
- node.js - 如何从反应客户端向运行在 Heroku 平台上的表达服务器发出 API 请求
- html - 使网格根据需要添加新列
- html - 了解表属性的特殊性
- android - 约束布局组的 Espresso 测试
- python - 有没有办法扭转熊猫的丢弃方法?
- python - 用 Python 替换 CSV 文件中的值