JavaScript   发布时间:2022-04-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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,但这可能是最近的一个补充.

大佬总结

以上是大佬教程为你收集整理的javascript eventemitter多次事件一次全部内容,希望文章能够帮你解决javascript eventemitter多次事件一次所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。