3.1.2 • Published 5 years ago
@a-z.ren/event-hub v3.1.2
Event Hub
Simple Event Hub
Table of Contents
Advantage
public subscriber: Map<string, Set<EventHandler>> = new Map();The EventHub uses Map and Set to store EventHandler. has better performance and more concise code to implement core functions than using Object and Array.
The disadvantage is that it only supports
ES6or above, and no longer has performance advantage after compiling toES5.
Install
npm i @a-z.ren/event-hubUsage
JavaScript
import EventHub from "@a-z.ren/event-hub";TypeScript
import EventHub from "@a-z.ren/event-hub/src/EventHub";Basic functions:
const eventHub = new EventHub();
function handlerA() {
console.log("I'm A!");
}
eventHub.on("1", handlerA);
eventHub.on("1", (a, b) => console.log(`I'm B, I like ${a} and ${b}!`));
eventHub.once("1", () => console.log("I'm C, I only be triggered once!"));
eventHub.emit("1", "🐱", "🐶");
// I'm A!
// I'm B, I like 🐱 and 🐶!
// I'm C, I only be triggered once!
eventHub.off("1", handlerA);
eventHub.emit("1", "🍦", "🍰");
// I'm B, I like 🍦 and 🍰!Promise and Async/Await:
(async function () {
const value = await eventHub.promise("2");
console.log("Await " + value);
})();
eventHub
.promise("2")
.then((value) => "Then " + value)
.then(console.log);
eventHub.emit("2", "Hello");
// Await Hello
// Then HelloExtends
class ChatCat extends EventHub {
sayHello() {
this.emit("say", "Hello!");
}
sayGood() {
this.emit("say", "Good!");
}
}
const cat = new ChatCat();
cat.on("say", console.log);
cat.sayHello();
// Hello!
cat.sayGood();
// Good!Gather
eventHub.on("4", (value) => "Love " + value);
eventHub.once("4", (value) => "Good " + value);
eventHub.gather("4", "gather").forEach((result) => console.log(result));
// Love gather
// Good gatherContribute
- Fork the repository
- Create Feat_xxx branch
- Commit your code
- Create Pull Request
License
MIT © A-Z.REn