Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add dispatchEvent to EventSource #101

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions lib/eventsource.js
Expand Up @@ -345,6 +345,22 @@ EventSource.prototype.addEventListener = function addEventListener (type, listen
}
}

/**
* Emulates the W3C Browser based WebSocket interface using dispatchEvent.
*
* @param {Event} event An event to be dispatched
* @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
* @api public
*/
EventSource.prototype.dispatchEvent = function dispatchEvent (event) {
if (!event.type) {
throw new Error('UNSPECIFIED_EVENT_TYPE_ERR')
}
// if event is instance of an CustomEvent (or has 'details' property),
// send the detail object as the payload for the event
this.emit(event.type, event.detail)
}

/**
* Emulates the W3C Browser based WebSocket interface using removeEventListener.
*
Expand Down
44 changes: 44 additions & 0 deletions test/eventsource_test.js
Expand Up @@ -1079,6 +1079,50 @@ describe('Events', function () {
}
})
})

it('throws error if the message type is unspecified, \'\' or null', function (done) {
createServer(function (err, server) {
if (err) return done(err)

var es = new EventSource(server.url)

assert.throws(function () { es.dispatchEvent({}) })
assert.throws(function () { es.dispatchEvent({type: undefined}) })
assert.throws(function () { es.dispatchEvent({type: ''}) })
assert.throws(function () { es.dispatchEvent({type: null}) })

server.close(done)
})
})

it('delivers the dispatched event without payload', function (done) {
createServer(function (err, server) {
if (err) return done(err)

var es = new EventSource(server.url)

es.addEventListener('greeting', function (m) {
server.close(done)
})

es.dispatchEvent({type: 'greeting'})
})
})

it('delivers the dispatched event with payload', function (done) {
createServer(function (err, server) {
if (err) return done(err)

var es = new EventSource(server.url)

es.addEventListener('greeting', function (m) {
assert.equal('Hello', m.data)
server.close(done)
})

es.dispatchEvent({type: 'greeting', detail: {data: 'Hello'}})
})
})
})

describe('Proxying', function () {
Expand Down