"बढ़ाएँ" इस तरह 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 जिसमें एक उदाहरण शामिल है (आपका उदाहरण, कुछ लॉग के साथ)
[अद्यतन] फोल
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));
});
};
मुझे पता चला Node.js पहले से ही EventEmitter में एक once
विधि है: lowing once
की मेरी कार्यान्वयन पर आधारित एक फिल्म है कि केवल घटना है कि, बुलाया गया था के रूप में टिप्पणी में अनुरोध को दूर करता है की जाँच here the source code, लेकिन यह शायद हाल ही में एक जोड़ा है।
यह वास्तव में 'removeListener' काम कर के रूप में यह पहले किया था से टूट जाता है। शायद यह जवाब ठीक करने के लिए विस्तारित किया जा सकता है। – Harry
क्या आप 'removeListener' को 'ईवेंट' तर्क के रूप में भेजे गए सभी ईवेंट की बजाय केवल ईवेंट को निकालने के लिए चाहते हैं? जैसे ही मुझे आपकी इच्छा के बारे में पता चल जाएगा, मैं अपना जवाब अपडेट करूंगा। – fableal
बस जो घटना भेजी गई थी वह बहुत अच्छी होगी। – Harry