最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

使用多种方法实现事件管理器

运维笔记admin11浏览0评论

使用多种方法实现事件管理器

使用多种方法实现事件管理器

实现EventManager类

  1. 推(事件:字符串,方法:函数)
  2. 删除(事件:字符串,方法:函数)
  3. 打印(事件:字符串,数据:somedata)
const channel = new EventManager;

const cb1 = data => console.log('Cb 1:', data);
const cb2 = data => console.log('Cb 2:', data);
const cb3 = data => console.log('Cb 3:', data);

channel.push('ERROR', cb1);
channel.push('ERROR', cb2);
channel.push('SUCCESS', cb3);

channel.print('ERROR', { foo: 'bar' });
channel.print('SUCCESS', { food: 'apple' });
// Cb 1: { foo: 'bar' }
// Cb 2: { foo: 'bar' }
// Cb 3: { food: 'apple' }

channel.remove('ERROR', cb1);
channel.print('ERROR', { bat: 'batt' });
// Cb 2: { bat: 'batt' }

我的想法是使用新的Map()来解决死循环问题,即地图的键是事件类型,值是函数列表

  1. 推送-将功能添加到列表中
  2. 删除-从列表中删除功能
  3. 打印-使用事件类型从地图获取列表,数据调用函数
var list = [];
var map = {}
function push(type, func) {
    list.add(func);
    map.set(type, list);
}
function remove(type, func) {
    list.remove(func);
    map.set(type, list);
}

我不知道如何实现“ print”方法,并且我不确定是否需要针对此问题使用一些回调?也不确定我的“推”和“移”是否在正确的轨道上]

回答如下:

您接近(不是真的)

class EventManager {
    constructor() {
        this.events = {};
    }
    subscribe(event, callback) {
        const map = this.events[event] = this.events[event] || new Map;
        if (typeof callback === 'function') {
            map.set(callback);
        }
    }
    publish(event, data) {
        const map = this.events[event];
        if (map) {
            [...map].forEach(([cb]) => cb(data));
        }        
    }
    unsubscribe(event, callback) {
        const map = this.events[event];
        if (map) {
            map.delete(callback);
        }
    }
}
channel = new EventManager;
const callback1 = data => console.log('Callback 1:', data);
const callback2 = data => console.log('Callback 2:', data);
const callback3 = data => console.log('Callback 3:', data);

channel.subscribe('request.error', callback1);
channel.subscribe('request.error', callback2);
channel.subscribe('request.success', callback3);

channel.publish('request.error', { foo: 'bar' });
channel.publish('request.success', { lorem: 'ipsum' });

// Expected output in console:
//
// Callback 1: { foo: 'bar' }
// Callback 2: { foo: 'bar' }
// Callback 3: { lorem: 'ipsum' }

channel.unsubscribe('request.error', callback1);
channel.publish('request.error', { bar: 'baz' });

// Expected output in console:
//
// Callback 2: { bar: 'baz' }
发布评论

评论列表(0)

  1. 暂无评论