diff --git a/lib/eventsource.js b/lib/eventsource.js index a386766..2ea326d 100644 --- a/lib/eventsource.js +++ b/lib/eventsource.js @@ -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); } }; diff --git a/test/eventsource_test.js b/test/eventsource_test.js index 79548e3..c75e17d 100644 --- a/test/eventsource_test.js +++ b/test/eventsource_test.js @@ -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);