Does TypeScript support events on classes?

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

    Here's a simple example of adding custom-type events to your class, using sub-events:

    class MyClass {
    
        readonly onMessage: SubEvent = new SubEvent();
        readonly onData: SubEvent = new SubEvent();
    
        sendMessage(msg: string) {
            this.onMessage.emit(msg);
        }
    
        sendData(data: MyCustomType) {
            this.onData.emit(data);
        }
    }
    

    And then any client can subscribe to receive those events:

    const a = new MyClass();
    
    const sub1 = a.onMessage.subscribe(msg => {
        // msg here is strongly-typed
    });
    
    const sub2 = a.onData.subscribe(data => {
        // data here is strongly-typed
    });
    

    And when you no longer need the events, you can cancel the subscriptions:

    sub1.cancel();
    
    sub2.cancel();
    

提交回复
热议问题