main-event
Typed event emitters
Last updated 11 hours ago by GitHub Actions .
Apache-2.0 OR MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install main-event 
SYNC missed versions from official npm registry.

main-event

codecov CI

Typed event emitters

About

Adds types to the EventTarget class.

Hopefully this won't be necessary forever:

In addition to types, a safeDispatchEvent method is available which prevents dispatching events that aren't in the event map, and a listenerCount method which reports the number of listeners that are currently registered for a given event.

Example

import { TypedEventEmitter } from 'main-event'
import type { TypedEventTarget } from 'main-event'

interface EventTypes {
  'test': CustomEvent<string>
}

const target = new TypedEventEmitter<EventTypes>()

// it's a regular EventTarget
console.info(target instanceof EventTarget) // true

// register listeners normally
target.addEventListener('test', (evt) => {
  // evt is CustomEvent<string>
})

// @ts-expect-error 'derp' is not in the event map
target.addEventListener('derp', () => {})

// use normal dispatchEvent method
target.dispatchEvent(new CustomEvent('test', {
  detail: 'hello'
}))

// use type safe dispatch method
target.safeDispatchEvent('test', {
  detail: 'world'
})

// report listener count
console.info(target.listenerCount('test')) // 0

// event emitters can be used purely as interfaces too
function acceptTarget (target: TypedEventTarget<EventTypes>) {
  // ...
}

Install

$ npm i main-event

Browser <script> tag

Loading this module through a script tag will make its exports available as MainEvent in the global namespace.

<script src="https://unpkg.com/main-event/dist/index.min.js"></script>

API Docs

License

Licensed under either of

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Current Tags

  • 1.0.4                                ...           latest (11 hours ago)

6 Versions

  • 1.0.4                                ...           11 hours ago
  • 1.0.3                                ...           13 hours ago
  • 1.0.2                                ...           15 hours ago
  • 1.0.1                                ...           10 months ago
  • 1.0.0                                ...           10 months ago
  • 0.0.0                                ...           10 months ago
Maintainers (1)
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 0
Dependencies (0)
None
Dev Dependencies (1)

Copyright 2013 - present © cnpmjs.org | Home |