I am just wondering if in TypeScript you can define custom events on your classes or interfaces?
What would this look like?
How about this simplified event to be used as a property? Stronger typing of the owning class and no inheritance requirement:
interface ILiteEvent {
on(handler: { (data?: T): void }) : void;
off(handler: { (data?: T): void }) : void;
}
class LiteEvent implements ILiteEvent {
private handlers: { (data?: T): void; }[] = [];
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 trigger(data?: T) {
this.handlers.slice(0).forEach(h => h(data));
}
public expose() : ILiteEvent {
return this;
}
}
used like so:
class Security{
private readonly onLogin = new LiteEvent();
private readonly onLogout = new LiteEvent();
public get LoggedIn() { return this.onLogin.expose(); }
public get LoggedOut() { return this.onLogout.expose(); }
// ... onLogin.trigger('bob');
}
function Init() {
var security = new Security();
var loggedOut = () => { /* ... */ }
security.LoggedIn.on((username?) => { /* ... */ });
security.LoggedOut.on(loggedOut);
// ...
security.LoggedOut.off(loggedOut);
}
Improvements?
A gist for this