Skip to content

Commit

Permalink
Add dispatchEvent to EventSource
Browse files Browse the repository at this point in the history
  • Loading branch information
Ali Afroozeh committed May 22, 2018
1 parent b009a96 commit f78f08f
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
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

0 comments on commit f78f08f

Please sign in to comment.