有没有办法在Node.js中“吃”事件?

有没有办法“吃”一个事件的其他听众?

x.on("test", function(x){ if(x==4) { console.log("Event1"); } }); x.on("test", function(x){ if(x==5) { console.log("Event2"); } }); x.on("test", function(x){ console.log("Event3"); }); x.emit("test", 4); x.emit("test", 5); x.emit("test", -1); 

有没有办法让事件1“吃”(不允许发生)其他事件,如果x是4?

如果(x!= 4 && x!= 5)没有添加到事件3(如果有很多听众,它可能会很快恼人)。

奖金:我可以有一个“后备”事件来捕捉没有任何监听者的事件。

内置于节点的EventEmitter不支持“吃”其他事件处理程序或具有“全部”事件处理程序。 如果您需要这种function,您将不得不使用npm上的其他EventEmitter实现之一。

你可以简单地尝试这个

  x.on("test", function(x){ switch(x){ case 4: console.log("Event1"); break; case 5: console.log("Event2"); break; default: console.log("Event3"); } }); x.emit("test", 4); x.emit("test", 5); x.emit("test", -1);