Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A type-safe marriage of `EventTarget` and `EventEmitter`.

License

NotificationsYou must be signed in to change notification settings

kettanaito/rettime

Repository files navigation

A type-safe marriage ofEventTarget andEventEmitter.

Features

  • 🎯Event-based. Control event flow: prevent defaults, stop propagation, cancel events. Something your commonEmitter can't do.
  • 🗼Emitter-inspired. Emit event types and data, don't bother with creatingEvent instances. A bit less verbosity than a commonEventTarget.
  • ⛑️Type-safe. Describe the exact event types and payloads accepted by the emitter. Never emit or listen to unknown events.
  • 🧰Convenience methods like.emitAsPromise() and.emitAsGenerator() to build more complex event-driven systems.
  • 🐙Tiny. 700B gzipped.

Warning

This librarydoes not have performance as the end goal. In fact, since it operates on events and supports event cancellation, it will likely beslower than the emitters that don't do that.

Motivation

Why not justEventTarget?

TheEventTarget API is fantastic. It works in the browser and in Node.js, dispatches actual events, supports cancellation, etc. At the same time, it has a number of flaws that prevent me from using it for anything serious:

  • Complete lack of type safety. Thetype innew Event(type) is not a type argument inlib.dom.ts. It's alwaysstring. It means it's impossible to narrow it down to a literal string type to achieve type safety.
  • No concept of.prependListener(). There is no way to add a listener to runfirst, before other existing listeners.
  • No concept of.removeAllListeners(). You have to remove each individual listener by hand. Good if you own the listeners, not so good if you don't.
  • No concept of.listenerCount() or knowing if a dispatched event had any listeners (theboolean returned from.dispatch() indicates if the event has been prevented, not whether it had any listeners).
  • (Opinionated) Verbose. I prefer.on() over.addEventListener(). I prefer passing data than constructingnew MessageEvent() all the time.

Why not justEmitter (in Node.js)?

TheEmitter API in Node.js is great, but it has its own downsides:

  • Node.js-specific.Emitter does not work in the browser.
  • Lacks any type safety.
  • No concept of.stopPropagation() and.stopImmediatePropagation(). Those methods are defined but literally do nothing.

Install

npm install rettime

API

TypedEvent

TypedEvent is a subset ofMessageEvent that allows for type-safe event declaration.

newTypedEvent<DataType,ReturnType,EventType>(type:EventType,{data:DataType})

Thedata argument depends on theDataType of your event. Usevoid if the event must not send any data.

Custom events

You can implement custom events by extending the defaultTypedEvent class and forwarding the type arguments that it expects:

classGreetingEvent<DataType=void,ReturnType=any,EventTypeextendsstring=string,>extendsTypedEvent<DataType,ReturnType,EventType>{publicid:string}constemitter=newEmitter<{greeting:GreetingEvent<'john'>}>()emitter.on('greeting',(event)=>{console.log(eventinstanceofGreetingEvent)// trueconsole.log(eventinstanceofTypedEvent)// trueconsole.log(eventinstanceofMessageEvent)// trueconsole.log(event.type)// "greeting"console.log(event.data)// "john"console.log(event.id)// string})

Emitter

newEmitter<EventMap>()

TheEventMap type argument allows you describe the supported event types, their payload, and the return type of their event listeners.

import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{hello:TypedEvent<string,number>}>()emitter.on('hello',()=>1)// ✅emitter.on('hello',()=>'oops')// ❌ string not assignable to type numberemitter.emit(newTypedEvent('hello',{data:'John'}))// ✅emitter.emit(newTypedEvent('hello',{data:123}))// ❌ number is not assignable to type stringemitter.emit(newTypedEvent('hello'))// ❌ missing data argument of type stringemitter.emit(newTypedEvent('unknown'))// ❌ "unknown" does not satisfy "hello"

Describing events

TheEmitter class requires a type argument that describes the event map. If you do not provide that argument, adding listeners or emitting events will produce a type error as your emitter doesn't have an event map defined.

An event map is an object of the following shape:

{[type:string]:TypedEvent}

Thetype is a string indicating the event type (e.g.greet orping). The array it accepts has two members:args describes the arguments accepted by this event (can also benever for events without arguments) andreturnValue is an optional type for the data returned from the listeners for this event.

Let's say you want to define agreet event that expects a user name as data and returns a greeting string:

import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{greet:TypedEvent<string,string>}>()emitter.on('greet',(event)=>{console.log(`Hello,${event.data}!`)})emitter.emit(newTypedEvent('greet',{data:'John'}))// "Hello, John!"

Here's another example where we define aping event that has no arguments but returns a timestamp for each ping:

constemitter=newEmitter<{ping:TypedEvent<void,number>}>()emitter.on('ping',()=>Date.now())constresults=awaitemitter.emitAsPromise(newTypedEvent('ping'))// [1745658424732]

Important

When providing type arguments to yourTypedEvents, youdo not need to provide theEventType argument—it will be inferred from your event map.

.on(type, listener[, options])

Adds an event listener for the given event type.

import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{hello:TypedEvent<string>}>()emitter.on('hello',(event)=>{// `event` is a `TypedEvent` instance derived from `MessageEvent`.console.log(event.data)})

All methods that add new listeners return anAbortController instance bound to that listener. You can use that controller to cancel the event handling, including mid-air:

constcontroller=emitter.on('hello',listener)controller.abort(reason)

All methods that add new listeners also accept an optionaloptions argument. You can use it to configure event handling behavior. For example, you can provide an existingAbortController signal as theoptions.signal value so the attached listener abides by your controller:

emitter.on('hello',listener,{signal:controller.signal})

Both the public controller of the event and your custom controller are combined usingAbortSignal.any().

.once(type, listener[, options])

Adds a one-time event listener for the given event type.

.earlyOn(type, listener[, options])

Prepends a listener for the given event type.

import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{hello:TypedEvent<void,number>}>()emitter.on('hello',()=>1)emitter.earlyOn('hello',()=>2)constresults=awaitemitter.emitAsPromise(newTypedEvent('hello'))// [2, 1]

.earlyOnce(type, listener[, options])

Prepends a one-time listener for the given event type.

.emit(type[, data])

Emits the given event with optional data.

import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{hello:TypedEvent<string>}>()emitter.on('hello',(event)=>console.log(event.data))emitter.emit(newTypedEvent('hello','John'))

.emitAsPromise(type[, data])

Emits the given event and returns a Promise that resolves with the returned data of all matching event listeners, or rejects whenever any of the matching event listeners throws an error.

import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{hello:TypedEvent<number,Promise<number>>}>()emitter.on('hello',async(event)=>{awaitsleep(100)returnevent.data+1})emitter.on('hello',async(event)=>event.data+2)constvalues=awaitemitter.emitAsPromise(newTypedEvent('hello',{data:1}))// [2, 3]

Unlike.emit(), the.emitAsPromise() methodawaits asynchronous listeners.

.emitAsGenerator(type[, data])

Emits the given event and returns a generator function that exhausts all matching event listeners. Using a generator gives you granular control over what listeners are called.

import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{hello:TypedEvent<string,number>}>()emitter.on('hello',()=>1)emitter.on('hello',()=>2)for(constlistenerResultofemitter.emitAsGenerator(newTypedEvent('hello',{data:'John'}),)){// Stop event emission if a listener returns a particular value.if(listenerResult===1){break}}

.listeners([type])

Returns the list of all event listeners matching the given event type. If no eventtype is provided, returns the list of all existing event listeners.

.listenerCount([type])

Returns the number of the event listeners matching the given event type. If no eventtype is provided, returns the total number of existing listeners.

.removeListener(type, listener)

Removes the event listener for the given event type.

.removeAllListeners([type])

Removes all event listeners for the given event type. If no eventtype is provided, removes all existing event listeners.

Types

This library also comes with a set of helper types to make your life easier.

Emitter.EventType

Returns theEvent type (or its subtype) representing the given listener.

import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{greeting:TypedEvent<'john'>}>()typeGreetingEvent=Emitter.EventType<typeofemitter,'greeting'>// TypedEvent<'john'>

Emitter.ListenerType

Returns the type of the given event's listener.

import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{greeting:TypedEvent<string,number[]>}>()typeGreetingListener=Emitter.ListenerType<typeofemitter,'greeting'>// (event: TypedEvent<string>) => number[]

TheListenerType helper is in itself type-safe, allowing only known event types as the second argument.

Emitter.ListenerReturnType

Returns the return type of the given event's listener.

import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{getTotalPrice:TypedEvent<Cart,number>}>()typeCartTotal=Emitter.ListenerReturnType<typeofemitter,'getTotalPrice'>// number

About

A type-safe marriage of `EventTarget` and `EventEmitter`.

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

[8]ページ先頭

©2009-2025 Movatter.jp