# 组件通信 - EventHub
当应用稍微复杂一点的时候, 组件之间的通信会变得很复杂. 这里使用 eventHub 来解决. 其背后的思想是发布-订阅模式.
# 实现一个简单的 eventHub
一个 eventHub 应该有监听事件和触发事件两个功能:
let fnList = {}; const eventHub = { trigger() {}, on() {} };
Copied!
1
2
3
4
5
2
3
4
5
# on
on
函数用于监听事件:
on(eventName, fn){ if(!fnLists[eventName]){ fnLists[eventName] = [] } fnLists[eventName].push(fn) }
Copied!
1
2
3
4
5
6
2
3
4
5
6
我们传入事件名和回调函数, 当存放事件名的fnLists
里没有事件名则将以事件名为 key, 空数组为 value 的新的对象属性. 然后将回调加入数组里.
# trigger
trigger(eventName, data){ let fnList = fnLists[eventName] if (!fnList) {return} for (let i = 0; i < fnList.length; i++) { fnList[i](data) } }
Copied!
1
2
3
4
5
6
7
2
3
4
5
6
7
触发函数根据eventName
在fnLists
里找到对应数组并遍历执行数组里的函数.