Does TypeScript support events on classes?

后端 未结 8 736
小鲜肉
小鲜肉 2021-01-30 01:53

I am just wondering if in TypeScript you can define custom events on your classes or interfaces?

What would this look like?

8条回答
  •  心在旅途
    2021-01-30 02:33

    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

提交回复
热议问题