add bus class

This commit is contained in:
Géry Debongnie
2019-01-24 10:24:59 +01:00
parent 7761e699c1
commit 09ef8bb8c7
2 changed files with 61 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
type Callback = (...args: any[]) => void;
interface Subscription {
owner: any;
callback: Callback;
}
export default class Bus {
private subscriptions: { [eventType: string]: Subscription[] } = {};
on(eventType: string, owner: any, callback: Callback) {
if (!this.subscriptions[eventType]) {
this.subscriptions[eventType] = [];
}
this.subscriptions[eventType].push({
owner,
callback
});
}
off(eventType: string, owner: any) {
const subs = this.subscriptions[eventType];
if (subs) {
this.subscriptions[eventType] = subs.filter(s => s.owner !== owner);
}
}
trigger(eventType: string, ...args: any[]) {
const subs = this.subscriptions[eventType] || [];
for (let sub of subs) {
sub.callback(...args);
}
}
}
+29
View File
@@ -0,0 +1,29 @@
import Bus from "../src/ts/core/bus";
describe("event bus behaviour", () => {
test("can subscribe and be notified", () => {
const bus = new Bus();
let notified = false;
bus.on("event", {}, () => (notified = true));
expect(notified).toBe(false);
bus.trigger("event");
expect(notified).toBe(true);
});
test("can unsubscribe", () => {
const bus = new Bus();
let notified = false;
let owner = {};
bus.on("event", owner, () => (notified = true));
bus.off("event", owner);
bus.trigger("event");
expect(notified).toBe(false);
});
test("arguments are properly propagated", () => {
expect.assertions(1);
const bus = new Bus();
bus.on("event", {}, (arg: any) => expect(arg).toBe("hello world"));
bus.trigger("event", "hello world");
});
});