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

问题描述 投票:4回答:3

如何删除我在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>
javascript ecmascript-6 addeventlistener custom-element removeeventlistener
3个回答
4
投票

你当前的实现是不可能的 - 每次调用.bind都会创建一个新的单独函数,如果传递的函数与传递给removeEventListener的函数相同(===),你只能调用addEventListener去除一个监听器(就像.includes对于数组一样) ,或.has for Sets):

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' });
<button is="my-el" type="button">Click me</button>

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>

0
投票

另一种模式是将Listener保留在构造函数中。

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

由于在listen范围内调用remove函数,它使用相同的namefunction

伪代码:

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

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

  //cleanup:
  remove();

运行下面的代码片段,看它是否与多个按钮一起使用

Events bubbling UP & shadowDOM

一旦你做了更多的活动,为你节省一个小时......

请注意,WebComponents(即带有shadowDOM的CustomElements)需要具有composed:true属性的CustomEvents,如果您希望它们通过其shadowDOM边界向上冒泡

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

Removing added Event Listeners

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,但可用于构造函数范围内定义的所有函数。所以它(有点)私有,只有click功能可以更新它。
  • onclick=Two.disconnectedCallback()就像函数不删除元素一样。
© www.soinside.com 2019 - 2024. All rights reserved.