|
详细实现和测试用例, 请查看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不会通知该方法'); |
|
最新喜欢: |
|
沙发#
发布于:2020-06-15 09:15
|
|
|