定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| let instance = null const listeners = {}
class EventBus { static getInstance = () => { if (instance) { return instance } instance = new EventBus() return instance }
on = (event, fn) => { if (listeners[event]) { listeners[event].push(fn) } else { listeners[event] = [fn] } }
emit = (event, data) => { try { listeners[event].map(fn => fn(data)) } catch (error) { throw error } }
off = (event) => { delete listeners[event] } }
const eventBus = EventBus.getInstance();
eventBus.on('click', (data) => { console.log(data) })
eventBus.emit('click', 1000)
eventBus.off('click')
export default eventBus;
|