【JavaScript】手写发布订阅

【JavaScript】手写发布订阅

const eventHub = {
    map: {},
    on: (key, fn) => {
        eventHub.map[key] = eventHub.map[key] || [];
        eventHub.map[key].push(fn);
    },
    off: (key, fn) => {
        let mark = eventHub.map[key];
        if (!mark) {
            return
        }
        const index = mark.indexOf(fn);
        if (index < 0) {
            return
        }
        eventHub.map[key].splice(index, 1);
    },
    emit: (key, requestData) => {
        let mark = eventHub.map[key];
        if (!mark) {
            return
        }
        mark.map((fn) => {
            fn.call(undefined, requestData)
        });
    }
}

// 任务预置队列
eventHub.on('click', (requestData) => console.log(requestData));
eventHub.on('click', (requestData) => console.error(requestData));

setTimeout(() => {
    eventHub.emit('click', '提交')
}, 3000)