What are the differences between EventEmitter, EventTarget and EventDispatcher
Asked Answered
O

2

14

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?

Ore answered 25/10, 2017 at 11:21 Comment(0)
B
4

You can easily find documentation about all of them I think:

  • EventTarget - quite simple implementation to use in browsers
  • EventEmitter - native nodejs implemetation, rich on functionality
  • EventDispatcher - one of many implementations, used mostly in PHP
Belia answered 25/3, 2021 at 18:13 Comment(0)
G
2

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')
}
Glorygloryofthesnow answered 8/6, 2022 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.