Custom listenable
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 }>()