图片描述

原来通信模式没有规律,向一张纵横交错的网
图片描述

观察者模式: 数据总线
图片描述

class Emitter {
    _subs: {};
    construtor (params?: object) {
        return(params && this.mixin(params));
    }
    
    mixin (params) {
       for (let key in Emitter.prototype) {
           params[key] = Emitter.prototype[key];
       }
       return params;     
    }
    
    on 
    once
    off 
    emit
    
}

on (event, fn) {
  (this._subs[event] = this._subs[event] || []).push(fn);
  return this;
}
once (event, fn) {
        function on () {
            this.off(event, fn);
            fn.apply(this, arguments);
        }
        
        on.fn = fn;
        this.on(event, on);
        return this;
}
emit (event, ...args?: any) {
        let callbacks = this._subs[event];
        callbacks.forEach((item)=>{
            item.apply(this.args);
        });
        return this;
}
// off
off (event, fn) {
        if (0 === arguments.length) {
            this._subs = {};
            return this;
        }
        
        let callbacks = this._subs[event];
        if (!callbacks || !callbacks.length === 0) return this;
        if (1 === arguments.length) {
            delete this._subs[event];
            return this;
        }
        
        let cb;
        for (let i = 0; i < callbacks.length; i++) {
            cb = callbacks[i];
            if (cb === fn || cb.fn === fn) {
                callbacks.splice(i, 1);
                break;
            }
        }
        return this;
}

有李
108 声望12 粉丝

通过注意生活中细节性的风景


下一篇 »
一方app