Does TypeScript support events on classes?

后端 未结 8 740
小鲜肉
小鲜肉 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

    This solution allows you to directly write the parameters in the function call instead of needing to wrap all your parameters in an object.

    interface ISubscription {
       (...args: any[]): void;
    }
    
    class PubSub {
        protected _subscribed : ISubscriptionItem[] = [];
    
        protected findSubscription(event : T) : ISubscriptionItem {
            this._subscribed.forEach( (item : ISubscriptionItem) =>{
                if (item.func==event)
                  return item;
            } );
            return null;
        }
    
        public sub(applyObject : any,event : T) {
            var newItem = this.findSubscription(event);
            if (!newItem) {
                newItem = {object : applyObject, func : event };
                this._subscribed.push(newItem);
                this.doChangedEvent();
            }
        }
        public unsub(event : T) {
            for ( var i=this._subscribed.length-1 ; i>=0; i--) {
                if (this._subscribed[i].func==event)
                    this._subscribed.splice(i,1);
            }
            this.doChangedEvent();
        }
        protected doPub(...args: any[]) {
            this._subscribed.forEach((item : ISubscriptionItem)=> {
                item.func.apply(item.object, args);
            })
        }
    
        public get pub() : T {
            var pubsub=this;
            var func=  (...args: any[]) => {
                pubsub.doPub(args);
            }
            return func;
        }
    
        public get pubAsync() : T {
            var pubsub=this;
            var func =  (...args: any[]) => {
                setTimeout( () => {
                    pubsub.doPub(args);
                });
            }
            return func;
        }
    
        public get count() : number {
            return this._subscribed.length
        }
    
    }
    

    Usage:

    interface ITestEvent {
        (test : string): void;
    }
    
    var onTestEvent = new PubSub();
    //subscribe to the event
    onTestEvent.sub(monitor,(test : string) => {alert("called:"+test)});
    //call the event
    onTestEvent.pub("test1");
    

提交回复
热议问题