Add EventEmitter.prototype.once
This commit is contained in:
parent
3cf4827ae0
commit
a6ee3bac85
@ -76,6 +76,14 @@ EventEmitter.prototype.addListener = function (type, listener) {
|
|||||||
|
|
||||||
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
|
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
|
||||||
|
|
||||||
|
EventEmitter.prototype.once = function (type, listener) {
|
||||||
|
var self = this;
|
||||||
|
self.on(type, function g () {
|
||||||
|
self.removeListener(type, g);
|
||||||
|
listener.apply(this, arguments);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
EventEmitter.prototype.removeListener = function (type, listener) {
|
EventEmitter.prototype.removeListener = function (type, listener) {
|
||||||
if ('function' !== typeof listener) {
|
if ('function' !== typeof listener) {
|
||||||
throw new Error('removeListener only takes instances of Function');
|
throw new Error('removeListener only takes instances of Function');
|
||||||
@ -112,4 +120,4 @@ EventEmitter.prototype.listeners = function (type) {
|
|||||||
this._events[type] = [this._events[type]];
|
this._events[type] = [this._events[type]];
|
||||||
}
|
}
|
||||||
return this._events[type];
|
return this._events[type];
|
||||||
};
|
};
|
||||||
|
20
test/simple/test-event-emitter-once.js
Normal file
20
test/simple/test-event-emitter-once.js
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
common = require("../common");
|
||||||
|
assert = common.assert
|
||||||
|
var events = require('events');
|
||||||
|
|
||||||
|
var e = new events.EventEmitter();
|
||||||
|
var times_hello_emited = 0;
|
||||||
|
|
||||||
|
e.once("hello", function (a, b) {
|
||||||
|
times_hello_emited++;
|
||||||
|
});
|
||||||
|
|
||||||
|
e.emit("hello", "a", "b");
|
||||||
|
e.emit("hello", "a", "b");
|
||||||
|
e.emit("hello", "a", "b");
|
||||||
|
e.emit("hello", "a", "b");
|
||||||
|
|
||||||
|
process.addListener("exit", function () {
|
||||||
|
assert.equal(1, times_hello_emited);
|
||||||
|
});
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user