A minimal library for implementing Event Emitter functionality.
- Written in Typescript
- Has no dependencies (e.g. jquery)
- Lightweight, 1KB
- Supports ES6
git clone https://github.com/arayutw/emitter.git
cd emitter
npm install
npm run build
npm install @arayutw/emitter
Please find various build files (esm, cjs, umd).
If you plan to use it as a package, it is recommended to use @arayutw/emitter-import. It is a minimal project with only TypeScript files that has the same contents as this repository.
npm install @arayutw/emitter-import
import Emitter from "@arayutw/emitter-import";
import Emitter from "<pathto>/emitter.esm"
<script src="https://unpkg.com/@arayutw/emitter@latest/dist/scripts/emitter.js"></script>
<script>
class A extends Emitter {}
</script>
class A extends Emitter {
constructor() {
super();
}
}
const a = new A;
const handler = (event) => {
// {target: a, type: "click", x: 12, y: 34}
console.log(event);
}
a.on("click", handler, {
once: false,
});
a.off("click", handler);
a.emit("click", {
x: 12,
y: 34,
});
off("*")
removes all events.
a.off("*");
Development with Typescript is also convenient. Please define Generics (two arguments) when extending it.
Argument | Example | Description |
---|---|---|
1 | A |
The value of event.target . |
2 | {eventName: {data1: number, data2: string}} |
An object where the keys are event names and the values are objects containing event data. The key names "type" and "target" are reserved. |
import Emitter from "{pathto}/emitter/src/scripts/index"
// The key names "type" and "target" are reserved.
type Events = {
eventName: {
eventData1: any
eventData2: any
}
click: {
x: number
y: number
}
mousedown: {
// some data
}
}
class A extends Emitter<A, Events> {
constructor() {
super();
}
}
const a = new A;
a.on("click", (event) => console.log(event));
// OK
a.emit("click", {
x: 1,
y: 2,
});
// NG
a.emit("click2", {
x: 1,
y: 2,
});
// NG
a.emit("click", {
x: "a",
y: 2,
});