0.2.1 • Published 1 year ago

custom-listenable v0.2.1

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

Custom listenable npm npm type definitions

Create custom listenable with addListener and removeListener methods.

Installation

npm install custom-listenable

Usage

import { listenable } from 'custom-listenable'

// Create listenable
const myListenable = listenable()

// Prepare callback for new data
const callback = (data) => {
	console.log('Listener called')
	console.log(data)
}

// Listen to new data
myListenable.addListener(callback)

// Stop listening after 5 seconds
setTimeout(() => {
	myListenable.removeListener(callback)
}, 5000)

// Emit data every second
setInterval(() => {
	const data = {
		random: Math.random(),
		date: new Date(),
	}
	myListenable.emit(data)
}, 1000)

// Listen once
myListenable.addListener(
	(data) => {
		console.log('Listener called once')
		console.log(data)
	},
	{ once: true },
)

TypeScript

You can specify type of data that will be emitted.

const myListenable = listenable<{ random: number; date: Date }>()