gpt4 book ai didi

javascript - 在 JS 兄弟类之间传递事件

转载 作者:行者123 更新时间:2023-12-03 03:19:17 26 4
gpt4 key购买 nike

对于我的许多 JS 类,我调用一个基本模式,用白色背景覆盖我的页面。最近,我尝试减少一些代码,并将模式放入它自己的类中。我遇到的问题是,当我从同级类调用模态类时,模态变量未注册。我和一些人交谈过,他们建议我研究多态性,但从我读到的内容来看,它似乎与父/子类关系(使用扩展)有关。我很好奇是否有一种简单的方法可以使用 vanilla JS 来通过类与 sibling 进行交流?如果这个问题被多次触及,我深表歉意,但我一直在四处寻找,但找不到我需要的东西。

class Modal {
constructor(modal){
this.modal = modal;
this.closeButton = modal.querySelector('.modal-close-button');
}

activate() {
this.modal.setAttribute('data-state', 'active');
document.body.setAttribute('data-state', 'inactive');
}

deactivate() {
this.modal.setAttribute('data-state', 'inactive');
document.body.setAttribute('data-state', 'active');
}
}

class Form {
constructor(button, modal) {
this.button = button;
this.formId = button.getAttribute('data-form');
this.modal = modal;
this.setEvents();
}

setEvents() {
this.button.addEventListener('click', this.modal.activate);
}
}

最佳答案

最简单的修复方法是在构造函数中将this.activate绑定(bind)到this

class Modal {
constructor(modal){
this.modal = modal;
this.closeButton = modal.querySelector('.modal-close-button');
// add these two lines
this.activate = this.activate.bind(this);
this.deactivate = this.deactivate.bind(this);
}

activate() {
this.modal.setAttribute('data-state', 'active');
document.body.setAttribute('data-state', 'inactive');
}

deactivate() {
this.modal.setAttribute('data-state', 'inactive');
document.body.setAttribute('data-state', 'active');
}
}

或者,您可以更改 Form 类

class Form {
constructor(button, modal) {
this.button = button;
this.formId = button.getAttribute('data-form');
this.modal = modal;
this.setEvents();
}

setEvents() {
this.button.addEventListener('click', e => this.modal.activate(e));
}
}

关于javascript - 在 JS 兄弟类之间传递事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46637127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com