I'm trying to learn implementations of Observer Pattern.
EventEmitter/EventTarget/EventDispatcher are one implementation of Observer Pattern but I wonder the differences between these three.
Any help would be appreciated?
I'm trying to learn implementations of Observer Pattern.
EventEmitter/EventTarget/EventDispatcher are one implementation of Observer Pattern but I wonder the differences between these three.
Any help would be appreciated?
You can easily find documentation about all of them I think:
I would like to mention a detail difference when adding the same listener.
EventEmitter:
const EventEmitter = require('node:events')
const foo = new EventEmitter()
foo.on('event', listener)
foo.on('event', listener)
foo.emit('event')
// called: 1
// called: 2
function listener() {
console.count('called')
}
EventTarget:
const foo = new EventTarget()
foo.addEventListener('event', listener)
foo.addEventListener('event', listener)
foo.dispatchEvent(new Event('event'))
// called: 1
function listener() {
console.count('called')
}
// ------
const foo = new EventTarget()
foo.addEventListener('event', listener, { once: true })
foo.addEventListener('event', listener)
foo.dispatchEvent(new Event('event'))
foo.dispatchEvent(new Event('event'))
// called: 1
function listener() {
console.count('called')
}
// -----
const foo = new EventTarget()
foo.addEventListener('event', listener)
foo.addEventListener('event', listener, { once: true })
foo.dispatchEvent(new Event('event'))
foo.dispatchEvent(new Event('event'))
// called: 1
// called: 2
function listener() {
console.count('called')
}
© 2022 - 2024 — McMap. All rights reserved.