Class Observer<EventName>

This is a simple observer implementation for implementing synchronous in-process events for a local service.

You can use it like this:

enum FooEvent {
CHANGED = "FooService:changed"
}

class FooService {

private static _data : any;
private static _observer : Observer<FooEvent> = new Observer<FooEvent>("FooService");

public static getData () : any {
return this._data;
}

public static on (name : FooEvent, callback: ObserverCallback<FooEvent>) : ObserverDestructor {
return this._observer.listenEvent(name, callback);
}

public static refreshData () {
HttpService.doSomething().then((response) => {
this._data = response.data;
this._observer.triggerEvent(FooEvent.CHANGED);
}).catch(err => {
console.error('Error: ', err);
});
}

}

FooService.on(FooEvent.CHANGED, () => {

const currentData = FooService.getData();
// ...

});

FooService.refreshData();

Type Parameters

  • EventName extends keyof any

Hierarchy

  • Observer

Constructors

  • Creates a new Observer instance.

    Type Parameters

    • EventName extends string | number | symbol

    Parameters

    • name: string

      You can name this observer, so that you know where it is used.

    Returns Observer<EventName>

Properties

_callbacks: ObserverRecord<EventName>
_name: string

Methods

  • Removes all data associated with this Observer instance.

    After this method is called, the Observer instance should no longer be used.

    Returns void

  • Check if eventName has listeners.

    Parameters

    • eventName: EventName

    Returns boolean

  • Trigger an event

    Parameters

    • eventName: EventName
    • Rest ...args: any[]

    Returns void

  • Returns a Promise that is resolved when the specified event is triggered.

    Returns

    A Promise that is resolved when the specified event is triggered, or rejected with a timeout error if the event is not triggered within the specified timeout.

    Parameters

    • eventName: EventName

      The name of the event to wait for.

    • time: number

      The maximum amount of time (in milliseconds) to wait for the event before timing out.

    Returns Promise<void>

Generated using TypeDoc