In a previous tutorial I explained how events can be implemented as properties on a class using Strongly Typed Events for TypeScript. Let’s explore how to get events to work with interfaces.

Interfaces work a little different, because they don’t have getters and setters on them (at least not in TypeScript 1.8).

Interface implementation

Because interfaces don’t support getter-properties, we’ll need to use a method:

interface IClock {

    OnTick(): IEvent<IClock, number>;
}

Class implementation

Now create a clock that takes a interval and fires a tick each interval.

class Clock implements IClock {
    
    private _ticks = 0;
    private _onTick = new EventDispatcher<IClock, number>();
    
    constructor(interval: number) {
        var _this = this;
        setInterval(function () { _this.Tick(); }, interval);
    }

    private Tick(): void {
        this._ticks += 1;
        this._onTick.dispatch(this, this._ticks);
    }

    //implement method by returning the dispatcher as
    //an IEvent to hide the dispatch method
    OnTick() {
        return this._onTick.asEvent();
    }
}

Using the event handler

When the method is called an IEvent is returned. This event can be subscribed.

let clock: IClock = new Clock(5000);
clock.onTick().subscribe((sender, ticks) => alert('Tick-tock #' + ticks));

More

Check out the following: