观察者模式

161 阅读1分钟
class Observer {
    constructor() {
        this.events = {};
    }
    on(type, fn) {
        console.log('on');
        if (typeof type !== 'string') {
            throw new Error('not string');
        }
        if (!(fn instanceof Function)) {
            throw new Error('not function');
        }
        if (this.events[type] === undefined) this.events[type] = [];
        this.events[type].push(fn);
    }
    off(type, fn) {
        console.log('off');
        if (this.events[type] === undefined) {
            throw new Error('no such event');
        }
        this.events[type].forEach((f, index) => {
            console.log(f);
            console.log(fn);
            if (fn === f) this.events[type].splice(index, 1);
        });
    }
    subscribe(type, args) {
        if (this.events[type] && this.events[type].length > 0) {
            this.events[type].forEach((fn) => {
                fn.call(this, args);
            });
        } else {
            throw new Error('no such event');
        }
    }
}

var o = new Observer();
let showMsg = function(msg) {
    console.log('from ddd', msg);
}
o.on('ddd', showMsg);

o.subscribe('ddd', 'eee');

o.off('ddd', showMsg);

console.log(o);