Does TypeScript support events on classes?

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

    I think you are asking if a class instance can implement addEventListener() and dispatchEvent() like a DOM element. If the class is not a DOM node, then you would have to write your own event bus. You would define an interface for a class that can publish events, then implement the interface in the your classes. Here is a naive example;

    interface IEventDispatcher{
      // maintain a list of listeners
      addEventListener(theEvent:string, theHandler:any);
    
      // remove a listener
      removeEventListener(theEvent:string, theHandler:any);
    
      // remove all listeners
      removeAllListeners(theEvent:string);
    
      // dispatch event to all listeners
      dispatchAll(theEvent:string);
    
      // send event to a handler
      dispatchEvent(theEvent:string, theHandler:any);
    }
    
    class EventDispatcher implement IEventDispatcher {
      private _eventHandlers = {};
    
      // maintain a list of listeners
      public addEventListener(theEvent:string, theHandler:any) {
        this._eventHandlers[theEvent] = this._eventHandlers[theEvent] || [];
        this._eventHandlers[theEvent].push(theHandler);
      }
    
      // remove a listener
      removeEventListener(theEvent:string, theHandler:any) {
        // TODO
      }
    
      // remove all listeners
      removeAllListeners(theEvent:string) {
        // TODO
      }
    
      // dispatch event to all listeners
      dispatchAll(theEvent:string) {
        var theHandlers = this._eventHandlers[theEvent];
        if(theHandlers) {
          for(var i = 0; i < theHandlers.length; i += 1) {
            dispatchEvent(theEvent, theHandlers[i]);
          }
        }
      }
    
      // send event to a handler
      dispatchEvent(theEvent:string, theHandler:any) {
        theHandler(theEvent);
      }
    }
    

提交回复
热议问题