javascript eventemitter多次事件一次

前端之家收集整理的这篇文章主要介绍了javascript eventemitter多次事件一次前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用节点的eventemitter,尽管其他事件库建议是受欢迎的.

如果触发几个事件,我想运行一个函数.应该听多个事件,但是如果任何一个事件触发,它们都被删除.希望这个代码示例演示了我正在寻找什么.

  1. var game = new eventEmitter();
  2. game.once(['player:quit','player:disconnect'],function () {
  3. endGame()
  4. });

最干净的处理方式是什么?

注意:需要单独删除绑定的函数,因为会有其他监听器绑定.

解决方法

“扩展”EventEmitter,如下所示:
  1. var EventEmitter = require('events').EventEmitter;
  2.  
  3. EventEmitter.prototype.once = function(events,handler){
  4. // no events,get out!
  5. if(! events)
  6. return;
  7.  
  8. // Ugly,but helps getting the rest of the function
  9. // short and simple to the eye ... I guess...
  10. if(!(events instanceof Array))
  11. events = [events];
  12.  
  13. var _this = this;
  14.  
  15. var cb = function(){
  16. events.forEach(function(e){
  17. // This only removes the listener itself
  18. // from all the events that are listening to it
  19. // i.e.,does not remove other listeners to the same event!
  20. _this.removeListener(e,cb);
  21. });
  22.  
  23. // This will allow any args you put in xxx.emit('event',...) to be sent
  24. // to your handler
  25. handler.apply(_this,Array.prototype.slice.call(arguments,0));
  26. };
  27.  
  28. events.forEach(function(e){
  29. _this.addListener(e,cb);
  30. });
  31. };

我在这里创造了一个要点:https://gist.github.com/3627823
其中包括一个示例(您的示例,有一些日志)

[UPDATE]
以下是对我的执行情况的一次调整,只会根据评论中的要求删除调用的事件:

  1. var EventEmitter = require('events').EventEmitter;
  2.  
  3. EventEmitter.prototype.once = function(events,but helps getting the rest of the function
  4. // short and simple to the eye ... I guess...
  5. if(!(events instanceof Array))
  6. events = [events];
  7.  
  8. var _this = this;
  9.  
  10. // A helper function that will generate a handler that
  11. // removes itself when its called
  12. var gen_cb = function(event_name){
  13. var cb = function(){
  14. _this.removeListener(event_name,cb);
  15. // This will allow any args you put in
  16. // xxx.emit('event',...) to be sent
  17. // to your handler
  18. handler.apply(_this,0));
  19. };
  20. return cb;
  21. };
  22.  
  23.  
  24. events.forEach(function(e){
  25. _this.addListener(e,gen_cb(e));
  26. });
  27. };

我发现node.js在EventEmitter中已经有一个方法:check here the source code,但这可能是最近的一个补充.

猜你在找的JavaScript相关文章