1.0.0 • Published 3 years ago

native-dom-events v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

DOM Events

A native, fast and tiny way to emit & handle events for browser

What is "native-dom-events" package

It works similar to the events node built-in module but it uses EventTarget DOM interface (but it doesn't change or control the DOM). It's not polyfill, because it has another API. If you want polyfill I recommend browserify. It works on Node, but it's slow. NodeEventTarget isn't slow itself but inheriting it and using their method is.

Instalation

Via NPM:

npm i native-dom-events

Via UNPKG

<script src="https://unpkg.com/native-dom-events"></script>

(Namespace Event is called Events in Browser)

TypeScript

The package has rich type definitions because it's written in TS.

Creating events

When creating EventEmitter, you should mention all events that will be used and the corresponding Event class. It works like that:

import Event from "";
const emitter = new Event.Emitter({
    usual: Event.create("usual"), // argument and key must be same
    mine: class MyEvent extends Event.Base {
        constructor(data) {
            super("mine") // name
            this.data = data;
        }
    }
})

Event.Emitter

on(type: string, listener: (e) => void)

emitter.on("mine", e => {
    console.log(e.data);
})

You can also provide property handler (no other handlers can be added)

emitter.onmine = e => {
    console.log(e.data);
}

once(type: string, listener: (e) => void)

Same as on, but it listens for the first event only. Property handlers not supported.

off(type?: string, listener?: (e) => void)

// removes all listeners
emitter.off();
// removes all listeners with given type
emitter.off("mine");
// removes given listener
emitter.off("mine", this.handler)
// removes property handler
emitter.off("onmine");

emit(event: string, ...args)

Args are equal to constructor of given event (Event.create returns constructor without any arguments)