import { isFunction } from '@src/utils' ; /**
 * 事件机制，类似 NodeJS Events 模块
 * 使用文档参考 https://taro-docs.jd.com/taro/docs/apis/about/events/
 */ export default class Events { private listenerMap : { [ eventName ] : Function [ ] ; } = { } ; param eventName param listeners on ( eventName , ... listeners ) { if ( ! this . listenerMap [ eventName ] ) { this . listenerMap [ eventName ] = [ ] ; } for ( const listener of listeners ) { if ( isFunction ( listener ) ) { this . listenerMap [ eventName ] . push ( listener ) ; } } return this ; } param eventName param listener off ( eventName ? , listener ? ) { if ( ! eventName ) { this . listenerMap = { } ; return this ; } if ( ! listener ) { this . listenerMap [ eventName ] = [ ] ; return this ; } const container = this . listenerMap [ eventName ] ; const index = container . indexOf ( listener ) ; if ( index !== - 1 ) { container . splice ( index , 1 ) ; } return this ; } param eventName param args trigger ( eventName , ... args ) { const listeners = this . listenerMap [ eventName ] ; if ( Array . isArray ( listeners ) ) { listeners . forEach ( ( listener ) => { listener ( ... args ) ; } ) ; } return this ; } }