• eventEmitter 简单实现


    class EventEmmiter {
        constructor() {
            this._events = {}
        }
        on(type, cb) {
            if(Array.isArray(type)) {
                type.forEach(tp => this.on(tp, cb))
            } else {
                (this._events[type] || (this._events[type] = [])).push(cb);
                return this;
            }
        }
        emit(type) {
            const cbs = this._events[type];
            const args = Array.prototype.slice.call(arguments, 1);
            cbs && cbs.forEach(cb => cb.apply(this, args));
            return this;
        }
        off(type, cb) {
            if(!arguments.length) {
                this._events = new Object(null);
                return this;
            }
            if(Array.isArray(type)) {
                type.forEach(tp => this.off(tp, cb));
                return this;
            }
            if(!cb) {
                this._events[type] === null;
                return this;
            }
            if(cb) {
                const cbs = this._events[type];
                for(let len = cbs.length, i = len -1; i >= 0; i--) {
                    if(cbs[i] === cb || cbs[i].fn === cb) {
                        cbs.splice(i, 1);
                    }
                }
            }
            return this
        }
        once(type, cb) {
            function on() {
                this.off(type, cb);
                cb.apply(this, arguments);
            }
            on.fn = cb;
            this.on(type, on);
            return this;
        }
    }
    
  • 相关阅读:
    CF1137C Museums Tour(tarjan+DP)
    Educational Codeforces Round 65 (Rated for Div. 2)
    Codeforces Round #559(Div.1)
    委托
    类库
    is 和 as 运算符
    面向对象 接口
    抽象类
    面向对象 多态
    访问修饰符 程序集 静态方法
  • 原文地址:https://www.cnblogs.com/Mcrown/p/14435144.html
Copyright © 2020-2023  润新知