add initial macOS support #40
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
import { IEventSubscription } from './ISubscription';
|
||||
export interface ISignal<T> {
|
||||
on(handler: (data: T) => void): void;
|
||||
off(handler: (data: T) => void): void;
|
||||
on(handler: EventHandler<T>): IEventSubscription;
|
||||
}
|
||||
|
||||
export type EventHandler<T> = (data: T) => void;
|
||||
|
||||
3
src/infrastructure/Events/ISubscription.ts
Normal file
3
src/infrastructure/Events/ISubscription.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export interface IEventSubscription {
|
||||
unsubscribe(): void;
|
||||
}
|
||||
@@ -1,18 +1,28 @@
|
||||
import { ISignal } from './ISignal';
|
||||
export { ISignal };
|
||||
import { EventHandler, ISignal } from './ISignal';
|
||||
import { IEventSubscription } from './ISubscription';
|
||||
|
||||
export class Signal<T> implements ISignal<T> {
|
||||
private handlers: Array<(data: T) => void> = [];
|
||||
private handlers = new Map<number, EventHandler<T>>();
|
||||
|
||||
public on(handler: (data: T) => void): void {
|
||||
this.handlers.push(handler);
|
||||
}
|
||||
|
||||
public off(handler: (data: T) => void): void {
|
||||
this.handlers = this.handlers.filter((h) => h !== handler);
|
||||
public on(handler: EventHandler<T>): IEventSubscription {
|
||||
const id = this.getUniqueEventHandlerId();
|
||||
this.handlers.set(id, handler);
|
||||
return {
|
||||
unsubscribe: () => this.handlers.delete(id),
|
||||
};
|
||||
}
|
||||
|
||||
public notify(data: T) {
|
||||
this.handlers.slice(0).forEach((h) => h(data));
|
||||
for (const handler of Array.from(this.handlers.values())) {
|
||||
handler(data);
|
||||
}
|
||||
}
|
||||
|
||||
private getUniqueEventHandlerId(): number {
|
||||
const id = Math.random();
|
||||
if (this.handlers.has(id)) {
|
||||
return this.getUniqueEventHandlerId();
|
||||
}
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user