zclzye
侠客
侠客
  • 最后登录2025-01-01
  • 发帖数17
阅读:6608回复:1

[其它]面试: 请手写实现一个EventHub

楼主#
更多 发布于:2020-06-14 16:19
详细实现和测试用例, 请查看EventHub实现



实现源代码, 代码量非常少:


export default class EventHub {
    private caches = {};
    on(eventName, fn) {
        this.caches[eventName] = this.caches[eventName] || [];
        this.caches[eventName].push(fn);
    };

    off(eventName, fn) {
        const index = indexOf(this.caches[eventName], fn);
        if (index === -1) return;
        this.caches[eventName].splice(index, 1);
    };

    emit(eventName, data?) {
        (this.caches[eventName] || []).forEach(fn => fn(data));
    };
};

function indexOf(array, item) {
    let index = -1;
    if (!array) return index;
    for (let i = 0; i < array.length; i++) {
        if (array === item) {
            index = i;
            break;
        }
    }
    return index;
};




测试用例:




import EventHub from '../src';

const eventHub = new EventHub();
const test1 = desc => {
    console.assert(eventHub instanceof Object === true, desc);
    console.log('@help:', desc);
}

// on emit
const test2 = desc => {
    eventHub.on('xxx', function (data) {
        console.log('%cdata:', 'color: green', '注册的xxx方法被调用了', data);
        console.assert(data === '传一个数据');
    });
    eventHub.emit('xxx', '传一个数据');
    console.log('@help:', desc);
};

// off
const test3 = desc => {
    const eventHub2 = new EventHub();
    const fn1 = function () {
        console.log('注册的yyy被调用了');
    };
    eventHub2.on('yyy', fn1);
    eventHub2.off('yyy', fn1);
    eventHub2.emit('yyy');
    console.log('@help:', desc);
};

// test
test1('eventhub是一个对象');
test2('emit会触发on');
test3('on 之后可以off, emit不会通知该方法');

最新喜欢:

doubleyongdouble...
doubleyong
管理员
管理员
  • 最后登录2026-05-25
  • 发帖数1198
  • 最爱沙发
  • 喜欢达人
  • 原创写手
  • 社区居民
  • 忠实会员
沙发#
发布于:2020-06-15 09:15
知识需要管理,知识需要分享
游客


返回顶部

公众号

公众号