Skip to content

Commit

Permalink
Fix incorrect event emitter usage in removeEventListener
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Apr 17, 2017
1 parent cb532e7 commit 33aec48
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
19 changes: 14 additions & 5 deletions lib/eventsource.js
Original file line number Diff line number Diff line change
Expand Up @@ -280,24 +280,33 @@ Object.defineProperty(EventSource, 'CLOSED', { enumerable: true, value: 2});
/**
* Emulates the W3C Browser based WebSocket interface using addEventListener.
*
* @param {String} method Listen for an event
* @param {String} type A string representing the event type to listen out for
* @param {Function} listener callback
* @see https://developer.mozilla.org/en/DOM/element.addEventListener
* @see http://dev.w3.org/html5/websockets/#the-websocket-interface
* @api public
*/
EventSource.prototype.addEventListener = function addEventListener(method, listener) {
EventSource.prototype.addEventListener = function addEventListener(type, listener) {
if (typeof listener === 'function') {
// store a reference so we can return the original function again
listener._listener = listener;
this.on(method, listener);
this.on(type, listener);
}
};

EventSource.prototype.removeEventListener = function removeEventListener(method, listener) {
/**
* Emulates the W3C Browser based WebSocket interface using removeEventListener.
*
* @param {String} type A string representing the event type to remove
* @param {Function} listener callback
* @see https://developer.mozilla.org/en/DOM/element.removeEventListener
* @see http://dev.w3.org/html5/websockets/#the-websocket-interface
* @api public
*/
EventSource.prototype.removeEventListener = function removeEventListener(type, listener) {
if (typeof listener === 'function') {
listener._listener = undefined;
this.off(method, listener);
this.removeListener(type, listener);
}
};

Expand Down
24 changes: 24 additions & 0 deletions test/eventsource_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,30 @@ describe('Parser', function () {
});
});

it('allows removal of event listeners', function (done) {
createServer(function (err, server) {
if (err) return done(err);

server.on('request', writeEvents(["event: greeting\ndata: Hello\n\n", "event: greeting\ndata: World\n\n"]));
var es = new EventSource(server.url);
var numCalled = 0;

function onGreeting(m) {
numCalled++;
assert.equal("Hello", m.data);
es.removeEventListener('greeting', onGreeting, false);
process.nextTick(scheduleDisconnect);
}

function scheduleDisconnect() {
assert.equal(1, numCalled);
server.close(done);
}

es.addEventListener('greeting', onGreeting, false);
});
});

it('ignores comments', function (done) {
createServer(function (err, server) {
if (err) return done(err);
Expand Down

0 comments on commit 33aec48

Please sign in to comment.