如何在node.js / socket.io中使用removeListener来防止多重触发function

我有一个关于socket.io/node.js的问题。 我发送客户端到服务器,反之亦然,它触发我的function不止一个,即使我只是触发一次。 所以这是我的代码

客户端;

for (var x = circles.length - 1; x >= 0; x--) { if (circle.eat(circles[x])) { position = { x: circles[x].position.x, y: circles[x].position.y, r: circles[x].position.r, index: x }; circles.splice(x, 1); socket.emit('eat', position); //Here's the emit to server. } } 

服务器端;

 var events = require('events'); var eventEmitter = new events.EventEmitter(); socket.on('eat', function(data){ circlePosition.splice(data.index, 1); counter++; eventEmitter.removeListener('eat', this); //Removing this listener but planning to use it again by adding it again using addListener }); 

我已经试图比较传入的数据和最近发送的数据,以避免数据重复,即使它会被多次触发,但仍然会出现问题,如果使用这种方法,数据的精度将成为问题。 所以我试图使用removeListener和addListener,但错误是;

在这里输入图像说明

如何摆脱这个?

编辑

我试图让listenvariables一次从客户端发送到服务器,这里的代码

客户端:

 for (var x = circles.length - 1; x >= 0; x--) { if (circle.eat(circles[x])) { position = { x: circles[x].position.x, y: circles[x].position.y, r: circles[x].position.r, index: x, listen: false //Condition to if else in server side }; circles.splice(x, 1); socket.emit('eat', position); //Here's the emit to server. } } 

服务器端:

 socket.on('eat', eatFunction); function eatFunction(data){ if(!data.listen){ //listen variable used inside the if else block circlePosition.splice(data.index, 1); counter++; data.listen = null; console.log(data.listen + " " + counter); //to see if the listen becomes null and the counter to see how many times it triggers eventEmitter.removeAllListeners('eat', eatFunction); } } 

我认为问题是客户端,因为它发送超过它应该,而不是接收。

看这条线:

 eventEmitter.removeListener('eat', this); 

你认为this是什么意思? 看来你认为它是指这个函数,但事实并非如此。 JavaScript中的this关键字可能有点棘手,但基本上它会引用包含函数的实例,而不是函数本身。

您需要传递函数本身的引用。 如果停止使用内联函数并使用命名函数,则可能会更容易:

 socket.on('eat', eatFunction); function eatFunction(data){ circlePosition.splice(data.index, 1); counter++; eventEmitter.removeListener('eat', eatFunction); } 

请注意, eatFunction()现在有一个名称,因此您可以将它用作on()removeListener()函数的参数。

无耻的自我推销:我写了一个关于在这里创buildJavaScript函数的教程。

编辑:如果你所要做的只是事件的最高反应,为什么不使用一个跟踪你是否应该对事件作出反应的variables呢? 像这样的东西:

 var listen = true; socket.on('eat', eatFunction); function eatFunction(data){ if(listen){ circlePosition.splice(data.index, 1); counter++; listen = false; } }