实现一个简单的发布订阅

157 阅读1分钟
        class eventEmiter {
            constructor() {
                this.subscribers = {};
            }
            _on(type, fn) {
                if(!this.subscribers[type]) {
                    this.subscribers[type] = [];
                }
                this.subscribers[type].push(fn);
            }
            _emit(type, ...param) {
                let fnList = this.subscribers[type];
                if(!fnList || !fnList.length) {
                    throw new Error('params is empty or Not a function!');
                }
                fnList.forEach((item) => {
                    item.call(this, ...param);
                })
            }
            _off(type, fn) {
                let cur  = this.subscribers[type];
                if(cur) {
                    this.subscribers[type] = this.subscribers[type].filter(item => item !== fn);
                }
            }
            _once(type, fn) {
                let _this = this;
                function _fn() {
                    fn.apply(_this, arguments);
                    _this._off(type, _fn);
                }
                _this._on(type, _fn);
            }
        }
        const event = new eventEmiter();
        function likeColor(color) {
            console.log('喜欢的颜色:', color);
        }
        event._once('color', likeColor);
        event._emit('color', '黑色');
        event._emit('color', '黑色');