您可以使用 bind() 或在 Node.js 中使用 Arrow Function。箭头函数将从调用上下文继承它们的执行上下文,这类似于bind() 的工作方式并提供相同的功能。
this.listener.removeListener('eventName', this.onChange)
如果在removeListener(eventName) 样式函数中调用它,则上述删除侦听器的方法将不起作用,如下所示:
const obj = new MyObject()
obj.init()
// This would blow up with a
// ReferenceError saying you cant call removeListener() on undefined
obj.listener.removeListener('event')
当您可以使用 constructor 和 class 语法时,不确定是否使用 init() 函数。
constructor() {
this.listener = new EventEmitter()
this.boundEventNameHandler = () => this.onChange()
this.listener.on('eventName', this.boundEventNameHandler)
}
您可以使用绑定函数在使用this 的类的上下文中删除侦听器。
let boundEventNameHandler = this.boundEventNameHandler
this.listener.removeListener('eventName', this.boundEventNameHandler)`
实现的示例如下所示
const EventEmitter = require('events')
class MyObject {
constructor () {
this.listener = new EventEmitter()
this.boundEventNameHandler = () => this.onChange()
this.listener.on('eventName', this.boundEventNameHandler)
}
// I would reconsider making this a property of the MyObject class
// instead, make onChange() a local function outside the MyObject
// class definition because onChange in this example is only used by the
// event listener for 'eventName'
onChange () {
console.log('event fired change')
}
removeListeners () {
let boundEventNameHandler = this.boundEventNameHandler
this.listener.removeListener('eventName', boundEventNameHandler)
}
}