Har*_*rry 14 javascript javascript-events node.js eventemitter
虽然欢迎其他事件库建议,但我正在使用node的eventemitter.
如果触发了几个事件,我想运行一次函数.应该监听多个事件,但如果任何一个事件触发,则会删除所有事件.希望此代码示例演示我正在寻找的内容.
var game = new eventEmitter();
game.once(['player:quit', 'player:disconnect'], function () {
endGame()
});
Run Code Online (Sandbox Code Playgroud)
处理这个问题的最简洁方法是什么?
注意:需要单独删除绑定函数,因为将绑定其他侦听器.
像这样"扩展"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);
});
};
Run Code Online (Sandbox Code Playgroud)
我在这里创建了一个要点:https://gist.github.com/3627823 其中包含一个示例(您的示例,包含一些日志)
[ UPDATE ]以下是对我的实现的修改once,它只删除了注释中所请求的被调用事件:
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;
// 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, Array.prototype.slice.call(arguments, 0));
};
return cb;
};
events.forEach(function(e){
_this.addListener(e, gen_cb(e));
});
};
Run Code Online (Sandbox Code Playgroud)
我发现node.js已经once在EventEmitter中有一个方法:在这里查看源代码,但这可能是最近添加的.
像这样的事情怎么样:
var game = new EventEmitter();
var handler = function() {
game.removeAllListeners('player:quit');
game.removeAllListeners('player:disconnect');
endGame();
};
game.on('player:quit', handler);
game.on('player:disconnect', handler);
Run Code Online (Sandbox Code Playgroud)
您可以编写一个包装器on,removeAllListeners以便能够传入数组(例如,循环数组并为每个元素调用onor removeAllListeners)。
| 归档时间: |
|
| 查看次数: |
14465 次 |
| 最近记录: |