首页 > 解决方案 > 避免循环依赖:替换事件的导入?

问题描述

我将一个文件代码拆分为多个文件代码,并且遇到了一些循环依赖项。

其中一些,我可以通过重构来避免它们,另一些看起来更复杂,或者对我来说没有意义,因为重构可能意味着必须将大量代码放在同一个文件中,而不是按特性/功能拆分它。

我已经看到其他组件使用事件在模块之间进行通信,我认为我可以使用相同的技术来避免循环依赖,但是....我不确定这是否只是一个丑陋的黑客而不是正确的方法正在做。

因此,例如,具有以下内容:

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);
}

...

这会是一个适当的解决方案吗?或者只是一个丑陋的黑客来“删除”循环依赖?

标签: javascriptes6-modulescircular-dependencycircular-reference

解决方案


推荐阅读