javascript removeEventListener不能在类中工作 [英] javascript removeEventListener not working inside a class

查看:379
本文介绍了javascript removeEventListener不能在类中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩es6类,并尝试设置一个简单的鼠标类。

I've been playing around with es6 classes, and tried setting up a simple mouse class.

addEventListener 可以工作,但由于某种原因,我无法使用 removeEventListener 。我猜这与上下文绑定有关,但我不知道如何解决这个问题。

addEventListener works, but for some reason I'm unable to remove them with removeEventListener. I'm guessing this has something to do with context binding, but I can't figure out how to fix this.

'use strict'
class Mouser {
    constructor() {
        this.counter = 0
        this.clicked = function (event) {
            this.counter++
            console.log('clicks:', this.counter)
            if (this.counter >= 10) this.remove()
        }
        window.addEventListener('click', this.clicked.bind(this))
    }

    remove() {
        console.log('Removing click listener') // this line runs ..
        window.removeEventListener('click', this.clicked.bind(this))
    }
}

var mouse = new Mouser()


推荐答案

每次调用 this.clicked.bind ,它返回一个新的和不同的函数。因此,传递给 addEventListener()的函数与传递给 removeEventListenter()因此,删除没有找到匹配,并且不删除任何东西。您必须将完全相同的函数传递给两者,才能使删除工作。

Each time you call this.clicked.bind(this), it returns a new and different function. Thus, the function you are passing to addEventListener() is not the same as the function you are passing to removeEventListenter() so thus the remove does not find a match and does not remove anything. You must pass the exact same function to both for the remove to work.

您必须创建一个本地存储的引用所使用的函数,通过相同的一个添加和删除。有很多方法可以做到这一点,但由于这是面向对象的代码,你将需要在对象本身存储引用,因此每个对象可以有自己的引用。

You will have to create a locally stored reference to the function you're using so that you can pass the same one to add and remove. There are a number of ways to do that, but since this is object oriented code, you will want to store the reference in the object itself so each object can have its own reference.

这里有一种方法:

'use strict'
class Mouser {
  constructor () {
    this.counter = 0
    this.clicked = function (event) {
      this.counter ++
      console.log('clicks:', this.counter)
      if (this.counter >= 10) this.remove()
    }
    // save the click handler so it can be used in multiple places
    this.clickHandler = this.clicked.bind(this);
    window.addEventListener('click', this.clickHandler)
  }

  remove () {
    console.log('Removing click listener') // this line runs ..
    window.removeEventListener('click', this.clickHandler)
  }
}

var mouse = new Mouser()

这篇关于javascript removeEventListener不能在类中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆