手动封装事件订阅

const eventList = {}
const $on = (eventName,callback) => {
  if(!eventList[eventName]){
     eventList[eventName] = []  
  }  
     eventList[eventName].push(callback)  
}
const $emit = (eventName,params) => {
  if(eventList[eventName]){
     let arr = eventList[eventName]
     arr.map((cb) => {
        cb(params)
     })  
  }  
}
const $off = (eventName,callback) => {
  if(eventList[eventName]){
     if(callback){
        let index = eventList[eventName].indexOf(callback)
        eventList[eventName].splice(index,1)
     } else {
        eventList[eventName].length = 0
     }  
   }  
}        
export default {
  $on,
  $emit,
  $off
}

 

posted @ 2020-12-20 20:19  `Duet`  阅读(75)  评论(0编辑  收藏  举报