@divine-dkh/lazy-emitter

A lazy event emitter

Usage no npm install needed!

<script type="module">
  import divineDkhLazyEmitter from 'https://cdn.skypack.dev/@divine-dkh/lazy-emitter';
</script>

README

LazyEmitter

A lazy event emitter

Installation

npm install @divine-dkh/lazy-emitter

Examples

Example 1

import LazyEmitter from '@divine-dkh/lazy-emitter';

const emitter = new LazyEmitter();

// Time origin
const origin = Date.now();

emitter.on('test', (message: string): void => {
    console.log(Date.now() - origin, message);
});

emitter.emit('test', 'immediately printed');
// If a lazy event is emitted,
// the previous lazy event of the same type, if exists,
//     will get discarded
emitter.emitAfter(1000, 'test', 'should not be printed');
emitter.emitAfter(1000, 'test', 'should be printed');
// setTimeout is to wait till the above event gets emitted
setTimeout(() => {
    emitter.emitAfter(1000, 'test', 'should be printed after another 1s');
}, 1000);
// => 0 'immediately printed'
//    1004 'should be printed'
//    2007 'should be printed after another 1s'

Example 2

import LazyEmitter from '@divine-dkh/lazy-emitter';

class Storage extends LazyEmitter {
    private dataOnHold: Map<string, string> = new Map();

    constructor(public storageArea: string) {
        super();

        // An event flushData will be emitted
        //     1s after the last Storage.set() call
        // Storage actually flushes data to disk on such events
        this.on('flushData', this.flushData);
    }

    public set(key: string, value: string): void {
        // Leave data on hold for now
        this.dataOnHold.set(key, value);

        // and flush data to disk later
        this.emitAfter(1000, 'flushData');

        console.log({ [key]: value }, 'on hold');
    }

    private flushData(): void {
        [ ...this.dataOnHold.entries() ].forEach(([ key, value ]) => {
            // Do something with { key: value }

            console.log({ [key]: value }, 'actually flushed to disk');
        });

        // All set
        this.dataOnHold.clear();
    }
}

const storage = new Storage('local');

// Remember input value on typing
input.addEventListener('keyup', (): void => {
    storage.set('value', input.value);
});
// Typing 'javascript' on the input...
//
// => { input: 'j' } 'on hold'
//    { input: 'ja' } 'on hold'
//    { input: 'jav' } 'on hold'
//    { input: 'java' } 'on hold'
//    { input: 'javas' } 'on hold'
//    { input: 'javasc' } 'on hold'
//    { input: 'javascr' } 'on hold'
//    { input: 'javascri' } 'on hold'
//    { input: 'javascrip' } 'on hold'
//    { input: 'javascript' } 'on hold'
//    { input: 'javascript' } 'actually flushed to disk'