我应该如何组织两个ES6类之间的交互,它们是否使用彼此的实例?
以下解决方案正在运行,但有点复杂。
let widgetA;
let widgetB = new WidgetB();
widgetA = new WidgetA(widgetB);
widgetB.initialize(widgetA);
class WidgetA {
constructor(widgetB){
this.widgetB = widgetB;
}
widgetAmethod(){
this.widgetB.doSomethingWidthWidgetB();
}
}
class WidgetB {
constructor(){
this.widgetA;
}
initialize(widgetA){
this.widgetA = widgetA;
}
widgetBmethod(){
this.widgetA.doSomethingWidthWidgetA();
}
}
我认为将实例传递到每个小部件会使代码过于紧密耦合,难以测试和扩展。在这些情况下,我更喜欢使用pub / sub或自定义事件:
let widgetA = new WidgetA();
let widgetB = new WidgetB();
class WidgetA {
constructor () {
document.addEventListener('widgetAsomething', this.doSomethingWidthWidgetA, false);
}
widgetAmethod () {
const event = new CustomEvent('widgetBsomething');
document.dispatchEvent(event);
}
doSomethingWithWidgetA () {}
}
class WidgetB {
constructor () {
document.addEventListener('widgetBsomething', this.doSomethingWidthWidgetB, false);
}
widgetBmethod () {
const event = new CustomEvent('widgetAsomething');
document.dispatchEvent(event);
}
doSomethingWithWidgetB () {}
}
这种方法有很多好处,未来的widgetC也可以轻松触发WidgetA和B方法。
有关自定义事件的更多信息,请访问:https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events