1. 程式人生 > 其它 >釋出訂閱者模式

釋出訂閱者模式

<script>   // 事件觸發器   class EventEmitter {     constructor () {       // { 'click': [fn1, fn2], 'change': [fn] }       this.subs = Object.create(null)     }
    // 註冊事件     $on (eventType, handler) {       this.subs[eventType] = this.subs[eventType] || []       this.subs[eventType].push(handler)     }
    // 觸發事件     $emit (eventType) {       if (this.subs[eventType]) {         this.subs[eventType].forEach(handler => {             handler()         })       }     } }
// 測試 let em = new EventEmitter() em.$on('click', () => {   console.log('click1') }) em.$on('click', () => {   console.log('click2') })
em.$emit('click') </script>