javascript eventemitter多次事件一次

我正在使用节点的eventemitter,尽管其他事件库建议是受欢迎的.

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

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

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

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

解决方法

“扩展”EventEmitter,如下所示:
var EventEmitter = require('events').EventEmitter;

EventEmitter.prototype.once = function(events,handler){
    // no events,get out!
    if(! events)
        return; 

    // Ugly,but helps getting the rest of the function 
    // short and simple to the eye ... I guess...
    if(!(events instanceof Array))
        events = [events];

    var _this = this;

    var cb = function(){
        events.forEach(function(e){     
            // This only removes the listener itself 
            // from all the events that are listening to it
            // i.e.,does not remove other listeners to the same event!
            _this.removeListener(e,cb); 
        });

        // This will allow any args you put in xxx.emit('event',...) to be sent 
        // to your handler
        handler.apply(_this,Array.prototype.slice.call(arguments,0));
    };

    events.forEach(function(e){ 
        _this.addListener(e,cb);
    }); 
};

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

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

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

EventEmitter.prototype.once = function(events,but helps getting the rest of the function 
    // short and simple to the eye ... I guess...
    if(!(events instanceof Array))
        events = [events];

    var _this = this;

    // A helper function that will generate a handler that 
    // removes itself when its called
    var gen_cb = function(event_name){
        var cb = function(){
            _this.removeListener(event_name,cb);
            // This will allow any args you put in 
            // xxx.emit('event',...) to be sent 
            // to your handler
            handler.apply(_this,0));
        };
        return cb;
    };


    events.forEach(function(e){ 
        _this.addListener(e,gen_cb(e));
    }); 
};

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...