丐版JS发布订阅模式

90 阅读1分钟
class Bus {
    const list = null;
    constructor() {
        this.list = {};
    }
    emit (name, ...arg) {
        const eventName = this.list[name];
        eventName.forEach((fn) => {
            fn.apply(this, arg)
        });
    }
    on (name, callback) {
        const fnlist = this.list[name] || [];
        fnlist.push(callback);
        this.list[name] = fnlist;
    }
}