我的代码结构就像一个中心辐射模型,我的大多数类都在作为集线器的Main类中实例化。特别是,我在Main类中有一个zoom方法,用于协调大多数其他类中的调用缩放方法。在其中一个辐条类中,我们称之为Buttons,我创建了一些按钮,用于触发Main中的zoom方法,并添加了事件监听器。我如何使用在按钮中创建的这些按钮来调用Main中的缩放方法而不将所有Main导入按钮?
Main.js看起来像这样:
import Header from './Header.js';
import ImageStrip from './ImageStrip.js';
import AreaChart from './AreaChart.js';
import Buttons from './Buttons.js';
class Main {
constructor() {
this.header = new Header();
this.imageStrip = new ImageStrip();
this.areaChart = new AreaChart();
this.buttons = new Buttons();
}
zoom(scale) {
this.imageStrip.zoom(scale);
this.areaChart.zoom(scale);
}
}
Buttons.js看起来像这样:
class Buttons {
constructor() {
const els = document.querySelectorAll('.buttons');
this.makeButtons(els);
}
makeButtons(buttons) {
buttons.forEach((button) => {
button.addEventListener('click', () => {
? call the zoom method in Main ?
})
})
}
export default Buttons;
答案 0 :(得分:0)
鉴于你并没有真正倾听事件,你只想调用一个方法,你应该将Main
的实例传递给Button
的构造函数。
这称为依赖注入。
答案 1 :(得分:-1)
Change Buttons class like this
class Buttons extends Main {
constructor() {
super();
const els = document.querySelectorAll('.buttons');
this.makeButtons(els);
}
makeButtons(buttons) {
buttons.forEach((button) => {
button.addEventListener('click', () => {
super.zoom();
})
})
}