gpt4 book ai didi

javascript - 类型错误 : listener must be a function

转载 作者:行者123 更新时间:2023-11-29 21:41:53 25 4
gpt4 key购买 nike

我在 WeakMap 中存储了一个事件监听器,并在检索函数以将其从 EventEmitter 中删除时抛出此错误:

TypeError: listener must be a function

我只是想不通问题是什么:

var EventEmitter = require('events').EventEmitter;

var listeners = new WeakMap();
var eventEmitterA = new EventEmitter();
var eventEmitterB = new EventEmitter();

eventEmitterA.on('open', (obj) => {
function stuff() { /* ... */ }

listeners.set(obj, stuff);

eventEmitterB.on('stuff', stuff);
});

eventEmitterA.on('close', (obj) => {
var listener = listeners.get(obj);

console.log(typeof listener); // logs "function"

eventEmitterB.removeListener(listener);
});


var someObject = {some: 'object'};

eventEmitterA.emit('open', someObject);
eventEmitterA.emit('close', someObject);

最佳答案

eventEmitterB.removeListener(listener);

应该是

eventEmitterB.removeListener('stuff', listener);

removeListener 有两个参数,函数应该是第二个参数,因此您将函数作为处理程序的名称传递,并将 undefined 作为处理程序传递。

关于javascript - 类型错误 : listener must be a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32512313/

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