1+ /**
2+ * 事件总线,跨界面通信解决方案
3+ * {eventName1:[listener1,listener2],eventName2:[listener3,listener4]}
4+ */
5+ export default class EventBus {
6+ static getInstance ( ) {
7+ if ( typeof EventBus . instance === 'object' ) {
8+ return EventBus . instance ;
9+ }
10+ return new EventBus ( ) ;
11+ }
12+
13+ constructor ( ) {
14+ if ( typeof EventBus . instance === 'object' ) {
15+ return EventBus . instance ;
16+ }
17+ EventBus . instance = this ;
18+ this . eventListeners = { } ;
19+ }
20+
21+ /**
22+ * 发送事件
23+ * @param eventName 事件名 string
24+ * @param data 要发送的数据
25+ */
26+ fireEvent ( eventName , data ) {
27+ let listeners = this . eventListeners [ eventName ] ;
28+ if ( Array . isArray ( listeners ) ) {
29+ listeners . map ( listener => {
30+ if ( typeof listener === 'function' ) {
31+ listener ( data ) ;
32+ }
33+ } )
34+ }
35+ }
36+
37+ /**
38+ * 注册事件监听器
39+ * @param eventName 事件名 string
40+ * @param listener 监听回调 function
41+ */
42+ addListener ( eventName , listener ) {
43+ let listeners = this . eventListeners [ eventName ] ;
44+ if ( Array . isArray ( listeners ) ) {
45+ listeners . push ( listener ) ;
46+ } else {
47+ this . eventListeners [ eventName ] = [ listener ] ;
48+ }
49+ }
50+
51+ /**
52+ * 移除监听器
53+ * @param listener 监听回调 function
54+ */
55+ removeListener ( listener ) {
56+ Object . keys ( this . eventListeners ) . map ( eventName => {
57+ let listeners = this . eventListeners [ eventName ] ;
58+ this . _remove ( listeners , listener ) ;
59+ if ( listeners . length === 0 ) {
60+ delete this . eventListeners [ eventName ] ;
61+ }
62+ } )
63+ }
64+
65+ /**
66+ * 将数组中指定元素移除
67+ * **/
68+ _remove ( array , item ) {
69+ if ( ! array ) return ;
70+ for ( let i = 0 , l = array . length ; i < l ; i ++ ) {
71+ if ( item === array [ i ] ) array . splice ( i , 1 ) ;
72+ }
73+ }
74+ }
0 commit comments