删除已使用bind(this)添加的事件侦听器

时间:2019-02-28 08:08:34

标签: javascript ecmascript-6 addeventlistener custom-element removeeventlistener

如何删除我在以下window中绑定到constructor的点击侦听器?我需要它来监听window,并且需要访问其中的按钮实例。

class MyEl extends HTMLButtonElement {
  constructor() {
    super();
    this.clickCount = 0;
    window.addEventListener('click', this.clickHandler.bind(this));
  }
  
  clickHandler(e) {
    if (e.target === this) {
      this.textContent = `clicked ${++this.clickCount} times`;
      window.removeEventListener('click', this.clickHandler);
    }
  }
  
  disconnectedCallback() {
      window.removeEventListener('click', this.clickHandler);
  }
}

customElements.define('my-el', MyEl, { extends: 'button' });
<button is="my-el" type="button">Click me</button>

3 个答案:

答案 0 :(得分:4)

当前的实现无法实现-每次调用.bind都会创建一个新的单独函数,并且如果传递的函数相同,则只能调用removeEventListener来删除侦听器({{1 }})作为传递给===的对象(就像addEventListener对于数组,或.includes对于集合):

.has

作为解决方法,您可以将绑定函数分配给实例的属性:

const fn = () => 'foo';
console.log(fn.bind(window) === fn.bind(window));
class MyEl extends HTMLButtonElement {
  constructor() {
    super();
    this.clickCount = 0;
    this.boundListener = this.clickHandler.bind(this);
    window.addEventListener('click', this.boundListener);
  }
  
  clickHandler(e) {
    this.textContent = `clicked ${++this.clickCount} times`;
    window.removeEventListener('click', this.boundListener);
  }
}

customElements.define('my-el', MyEl, { extends: 'button' });

答案 1 :(得分:1)

像这样为clickHandler创建包装函数。

class MyEl extends HTMLButtonElement {
  constructor() {
    super();
    this.clickCount = 0;
    this.wrapper = e => this.clickHandler.apply(this, e);
    window.addEventListener('click', this.wrapper);
  }
  
  clickHandler(e) {
    this.textContent = `clicked ${++this.clickCount} times`;
    
    window.removeEventListener('click', this.wrapper);
  }
}

customElements.define('my-el', MyEl, { extends: 'button' });
<button is="my-el" type="button">Click me</button>

答案 2 :(得分:0)

另一种模式是将监听器保留在构造函数内部。

要删除事件侦听器(无论采用哪种模式),可以在创建事件侦听器时添加“删除” 功能

由于在listen范围内调用了删除函数,因此它使用相同的namefunc功能

伪代码:

  listen(name , func){
    window.addEventListener(name, func);
    return () => window.removeEventListener( name , func );
  }

  let remove = listen( 'click' , () => alert('BOO!') );

  //cleanup:
  remove();

运行代码段,以查看它与多个按钮一起使用

冒泡UP和shadowDOM的事件

为您节省更多时间来完成活动……

请注意,如果您希望WebComponents(例如,带有 shadowDOM的CustomElements)具有composed:true属性的CustomEvent,则希望它们使向上越过其shadowDOM边界

    new CustomEvent("check", {
      bubbles: true,
      //cancelable: false,
      composed: true       // required to break out of shadowDOM
    });

删除添加的事件监听器

class MyEl extends HTMLButtonElement {
  constructor() {
    super();
    let count = 0;// you do not have to stick everything on the Element
    let ME = this;//makes code easier to read and minifies better!
    ME.mute = ME.listen('click' , event => {
      //this function is in constructor scope, so has access to ALL its contents
      if(event.target === ME) //because ALL click events will fire!
        ME.textContent = `clicked ${ME.id} ${++count} times`;
      //if you only want to allow N clicks per button you call ME.mute() here
    });
  }

  listen(name , func){
    window.addEventListener( name , func );
    console.log('added' , name , this.id );
    return () => { // return a Function!
      console.log( 'removeEventListener' , name , 'from' , this.id);
      this.style.opacity=.5;
      window.removeEventListener( name , func );
    }
  }
  eol(){ // End of Life
    this.parentNode.removeChild(this);
  }
  disconnectedCallback() {
      console.log('disconnectedCallback');
      this.mute();
  }
}

customElements.define('my-el', MyEl, { extends: 'button' });
button{
  width:12em;
}
<button id="One" is="my-el" type="button">Click me</button>
<button onclick="One.mute()">Mute</button> 
<button onclick="One.eol()">Delete</button> 
<br>
<button id="Two" is="my-el" type="button">Click me too</button>
<button onclick="Two.disconnectedCallback()">Mute</button> 
<button onclick="Two.eol()">Delete</button> 

注意:

  • count不能作为this.count使用,但可用于在构造函数范围内定义的所有函数。因此它是(kinda)私有的,只有click函数可以更新它。

  • onclick=Two.disconnectedCallback()仅作为该函数不会删除该元素的例子。