There are multiple ways to unsubscribe from an event. This page shows all the options using the following example:
import { EventDispatcher } from "strongly-typed-events";
class Clock {
private _onClockTick = new EventDispatcher<Clock, number>();
private _ticks: number = 0;
constructor(public name: string, timeout: number) {
setInterval(() => {
this._ticks += 1;
this._onClockTick.dispatch(this, this._ticks);
}, timeout);
}
public get onClockTick() {
return this._onClockTick.asEvent();
}
}
let clock = new Clock(1000);
You can unsubscribe using the event and calling unsub
or unsubscribe
.
let fn = (c: Clock, n: number) { };
clock.onClockTick.sub(fn);
clock.onClockTick.unsub(fn);
The sub
or subscribe
of the event will return an unsubscribe function.
let fn = (c: Clock, n:number) { };
let unsub = clock.onClockTick.sub(fn);
unsub();
The one
method of the event will only fire once and unsubscribe itself after firing.
let fn = (c: Clock, n:number) { };
clock.onClockTick.one(fn);
Each event gets an event management object as last parameter. You can use this object to unsubscribe the handler that caused the event.
clock.onClockTick.sub((c: Clock, n:number, ev:IEventManagement) => {
ev.unsub();
});