码迷,mamicode.com
首页 > 其他好文 > 详细

9.2发布订阅 es5

时间:2020-09-16 12:26:03      阅读:35      评论:0      收藏:0      [点我收藏+]

标签:more   cti   lte   事件   log   event   移除   new   name   

function Events(params) {
  this.events = []
  
}
//订阅
Events.prototype.on = function (eventName,eventFn) {
  if(!this.events[eventName]) {  //把事件存起来 ,有就push没有就创建新的
    this.events[eventName] = []
  }
  this.events[eventName].push(eventFn)
}
//发布
Events.prototype.emit  = function (eventName,msg) {
  if(this.events[eventName]){ //如果找到了这个事件就执行

    this.events[eventName].forEach(event => {
       //console.log(this.events)
      event(msg)
    })
  }
}
//退订
Events.prototype.removeEve = function (eventName,eventFn) {
  console.log(eventFn)
  if (this.events[eventName]) { //移除传过来的那个回调的事件
    this.events[eventName] = this.events[eventName].filter(event => {
      return event.name !== eventFn
    })
    console.log(this.events)
  }
}
let e = new Events()
e.on(‘say‘,function say(msg){
  console.log("hello---"+ msg)
})
e.on(‘sing‘,function sing(msg){
  console.log("hello---"+ msg)
})
e.on(‘eat‘,function eating(msg){
  console.log("hello---"+ msg)
})
e.on(‘eat‘,function eatmore(msg){
  console.log("delete---"+ msg)
})
// e.emit(‘say‘,‘say‘)
// e.emit(‘sing‘,‘sing‘)
// e.emit(‘eat‘,‘eat‘)
e.removeEve(‘eat‘,‘eatmore‘)
e.emit(‘say‘,‘say‘)
e.emit(‘sing‘,‘sing‘)
e.emit(‘eat‘,‘eat‘)
e.emit(‘eat‘,‘删除eatmore‘)

//输出
eatmore
[
  say: [ [Function: say] ],
  sing: [ [Function: sing] ],
  eat: [ [Function: eating] ]
]
hello---say
hello---sing
hello---eat
hello---删除eatmore

  

9.2发布订阅 es5

标签:more   cti   lte   事件   log   event   移除   new   name   

原文地址:https://www.cnblogs.com/zjj-study/p/13604917.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!