Skip to content

DispatchEvent

Andrei Fangli edited this page Sep 3, 2023 · 6 revisions
API / DispatchEvent<TEventArgs> class

DEPRECATED!

In future versions this class will be removed, switch to EventDispatcher, this is only a rename.


A base implementation of an event. To avoid misuse, declare a private event of this type and expose it as an IEvent<TEventArgs>.

Implements IEvent<TEventArgs>.

class DispatchEvent<TEventArgs = void> implements IEvent<TEventArgs>

Template Parameters

  • TEventArgs: optional, can be used to provide context when notifying subscribers.

Methods

  • subscribe: subscribes the given eventHandler to the event.
  • unsubscribe: unsubscribes the given eventHandler to the event. The exact same object that was used to subscribe to the event must be passed as well.
  • dispatch: dispatches a notification to all subscribers.

Example

This is a basic implementation of IEvent<TEventArgs> allowing instances to be wrapped as private fields and exposed as IEvent<TEventArgs> objects in order to allow users to only subscribe and unsubscribe from the event while only the object exposing the event can raise (dispatch) the event.

class MyObject {
    private readonly _myEvent: DispatchEvent = new DispatchEvent();

    public get myEvent(): IEvent {
        return this._myEvent;
    }

    public doSomething(): void {
        // some code
        this._meEvent.dispatch(this);
    }
}

const myObject = new MyObject();
myObject.myEvent.subscribe({
    handle(suject) {
        // handle event
    }
});

// myObject.myEvent.dispatch - does not work, IEvent does not expose a dispatch method.
myObject.doSomething();
Clone this wiki locally