TypeScript 是否支持类上的事件? [英] Does TypeScript support events on classes?

查看:28
本文介绍了TypeScript 是否支持类上的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道在 TypeScript 中是否可以在类或接口上定义自定义事件?

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

这会是什么样子?

推荐答案

这个简化的事件用作属性怎么样?拥有类的更强类型并且没有继承要求:

How about this simplified event to be used as a property? Stronger typing of the owning class and no inheritance requirement:

interface ILiteEvent<T> {
    on(handler: { (data?: T): void }) : void;
    off(handler: { (data?: T): void }) : void;
}

class LiteEvent<T> implements ILiteEvent<T> {
    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<T> {
        return this;
    }
}

像这样使用:

class Security{
    private readonly onLogin = new LiteEvent<string>();
    private readonly onLogout = new LiteEvent<void>();

    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);
}

改进?

这个要点

这篇关于TypeScript 是否支持类上的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆