gpt4 book ai didi

javascript - 无法扩展EventEmitter?

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:58 24 4
gpt4 key购买 nike

我正在尝试创建一个自定义事件发射器。看来我无法替换 onemit,如下所示。

  • 我尝试将方法分配给其他变量并使用它们,然后删除原始变量(不起作用)
  • 我尝试将 onemit 分配给不同的方法,例如 onTestemitTest(有效)

这是扩展 EventEmitter 的类:

import { EventEmitter } from 'events'

export default class MyEventEmitter extends EventEmitter {
constructor () {
super()
this._on = this.on
this._emit = this.emit
delete this.on
delete this.emit
}
on () {
this._on.apply(this, Object.values(arguments))
}
emit () {
this._emit.apply(this, Object.values(arguments))
}
}

let event = new MyEventEmitter()

event.on('hi', () => console.log('meow'))

event.emit('hi')

这是堆栈:

$ babel-node ./src/event-store/my-event-emitter.js 
/Users/thomas/.nvm/versions/node/v5.10.0/lib/node_modules/babel-cli/node_modules/babel-polyfill/node_modules/core-js/modules/es7.object.values.js:0



RangeError: Maximum call stack size exceeded
at Object.propertyIsEnumerable (native)
at /Users/thomas/.nvm/versions/node/v5.10.0/lib/node_modules/babel-cli/node_modules/babel-polyfill/node_modules/core-js/modules/_object-to-array.js:12:32
at values (/Users/thomas/.nvm/versions/node/v5.10.0/lib/node_modules/babel-cli/node_modules/babel-polyfill/node_modules/core-js/modules/es7.object.values.js:7:12)
at MyEventEmitter.emit (my-event-emitter.js:15:28)
at MyEventEmitter.emit (my-event-emitter.js:15:16)
at MyEventEmitter.emit (my-event-emitter.js:15:16)
at MyEventEmitter.emit (my-event-emitter.js:15:16)
at MyEventEmitter.emit (my-event-emitter.js:15:16)
at MyEventEmitter.emit (my-event-emitter.js:15:16)
at MyEventEmitter.emit (my-event-emitter.js:15:16)

更新 1

也尝试过此操作并收到相同的错误:

import { EventEmitter } from 'events'

export default class MyEventEmitter extends EventEmitter {
constructor () {
super()
}
on () {
this.on.apply(this, Object.values(arguments))
}
emit () {
this.emit.apply(this, Object.values(arguments))
}
}

let event = new MyEventEmitter()

event.on('hi', () => console.log('meow'))

event.emit('hi')

最佳答案

您尝试重新定义这些继承的方法最终会得到 this._emit === this.emit,这又会在调用中产生无限递归。

如果你想覆盖方法,你应该这样做。无需将它们重新分配给其他名称或尝试删除实例甚至没有的属性。

export default class MyEventEmitter extends EventEmitter {
on(...args) {
return super.on(...args)
}
emit(...args) {
return super.emit(...args);
}
}

(我认为那些 Object.values 调用毫无意义)

关于javascript - 无法扩展EventEmitter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37152286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com