Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在JS同级类之间传递事件_Javascript - Fatal编程技术网

Javascript 在JS同级类之间传递事件

Javascript 在JS同级类之间传递事件,javascript,Javascript,对于我的许多JS类,我调用了一个基本的模式,它以白色背景覆盖我的页面。最近,我尝试减少了一些代码,并将modal放入了自己的类中。我遇到的问题是,当我从同级类调用模态类时,模态变量没有注册。我和一些人谈过,他们建议我研究多态性,但从我所读到的内容来看,它似乎与父/子类关系有关(使用extend)。我很好奇香草JS是否有一种简单的方法可以通过类与兄弟姐妹进行通信?我很抱歉,如果这已经触及了很多,但我一直在寻找周围,无法找到我需要的 class Modal { constructor(modal

对于我的许多JS类,我调用了一个基本的模式,它以白色背景覆盖我的页面。最近,我尝试减少了一些代码,并将modal放入了自己的类中。我遇到的问题是,当我从同级类调用模态类时,模态变量没有注册。我和一些人谈过,他们建议我研究多态性,但从我所读到的内容来看,它似乎与父/子类关系有关(使用extend)。我很好奇香草JS是否有一种简单的方法可以通过类与兄弟姐妹进行通信?我很抱歉,如果这已经触及了很多,但我一直在寻找周围,无法找到我需要的

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。在
构造函数中激活
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');
  }
}
或者,您可以更改表单类

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

你的问题在于事件句柄中的
这个
是什么。你需要修复
表单#setEvents
模式中的任何句柄。谢谢你的帮助Jaromanda X,我想这是我在同一类中处理这个问题时通常使用的情况。function.bind(这个),但我不确定如何设置(这个)和我的莫代尔有关系。你介意详细说明吗?我已经添加了一个答案-你实际上根本不需要更改
setEvents
:pAh!谢谢你,这似乎奏效了。因此,基本上,如果我想从另一个类调用一个类方法,我必须在构造函数中添加一个.bind方法(如下所示);不。这与事件句柄有关,比如@JaromandaX的答案更好,但您也可以选择:
this.button.addEventListener('click',()=>this.modal.activate())是。我本来打算建议