1.1.0 • Published 3 years ago

picobus v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

picobus

Tiniest event bus possible, type-safe

// common base
import picobus from `picobus`
const bus = picobus<PayloadType>()

// subscriber
const callback = payload => handle(payload)
bus.listen(callback)
//…later, when it's not needed anymore
bus.unlisten(callback)

// publisher
bus.dispatch(payload)

Create a new bus for every event type:

const localeBus = picobus<Locale>()
const themeBus = picobus<Theme>()
const currentUserBus = picobus<UserData>()

Type Checking

Base case

const bus = picobus<boolean>()

bus.dispatch(true) // works
bus.dispatch(null) // TS error: Argument of type 'null' is not assignable to parameter of type 'boolean'.
bus.dispatch() // TS error: Expected 1 arguments, but got 0.

No payload

const bus = picobus()

bus.dispatch() // works
bus.dispatch(false) // TS error: Expected 0 arguments, but got 1.
bus.dispatch(null) // TS error: Expected 0 arguments, but got 1.

Optional payload

const bus = picobus<boolean | undefined>()

bus.dispatch(true) // works
bus.dispatch() // works
bus.dispatch(null) // TS error: Argument of type 'null' is not assignable to parameter of type 'boolean'.

Typing the Consumer

import { Picobus } from `picobus`

function consumeBus (bus : Picobus<boolean>) {
	bus.listen(payload => {
		// payload is now correctly typed 👍
		handleBoolean(payload)
	})
}

You can also import Picolistener and Picodispatch, depending on your use-case.

Need more features? Get a bigger bus:

1.1.0

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago