@untemps/event-dispatcher

1.2.0 • Public • Published

@untemps/event-dispatcher

Abstract class that allows to internally dispatch events and attach subscribers to listen for them.

.github/workflows/index.yml

Installation

yarn add @untemps/event-dispatcher

Usage

Import EventDispatcher:

import { EventDispatcher } from '@untemps/event-dispatcher'

Create a class that extends EventDispatcher:

class Foo extends EventDispatcher {
	constructor() {
		super()
	}

	foo() {
		this.dispatchEvent(new Event('foo', { bubbles: false, cancelable: false, composed: false }))
	}
}

Each instance can now attach a subscriber to listen for events:

const onFoo = (event) => console.log('foo has be triggered!')
const myFoo = new Foo()
myFoo.addEventListener('foo', onFoo)

And detach it:

myFoo.removeEventListener('foo', onFoo)

All subscriptions for a specific event type can be detached in batches:

const myFoo = new Foo()
myFoo.addEventListener('foo', onFoo1)
myFoo.addEventListener('foo', onFoo2)
myFoo.clearType('somethingDone')

All instance subscriptions can be detached in batches:

const myFoo = new Foo()
myFoo.addEventListener('foo', onFoo)
myFoo.addEventListener('bar', onBar)
myFoo.cleanup()

Todos

  • Add examples
  • Rewrite with TypeScript

Package Sidebar

Install

npm i @untemps/event-dispatcher

Weekly Downloads

0

Version

1.2.0

License

MIT

Unpacked Size

27.9 kB

Total Files

14

Last publish

Collaborators

  • untemps