/* Pubsub */
function Pubsub(){
  //存放事件和对应的处理方法
  this.handles = {};
} Pubsub.prototype = {
  //传入事件类型type和事件处理handle
  on: function (type, handle) {
    if(!this.handles[type]){
      this.handles[type] = [];
    }
    this.handles[type].push(handle);
  },
  emit: function () {
    //通过传入参数获取事件类型
    //将arguments转为真数组
    var type = Array.prototype.shift.call(arguments);
    if(!this.handles[type]){
      return false;
    }
    for (var i = 0; i < this.handles[type].length; i++) {
      var handle = this.handles[type][i];
      //执行事件
      handle.apply(this, arguments);
    }
  },
  off: function (type, handle) {
    handles = this.handles[type];
    if(handles){
      if(!handle){
        handles.length = 0;//清空数组
      }else{
      for (var i = 0; i < handles.length; i++) {
        var _handle = handles[i];
        if(_handle === handle){
          //从数组中删除
          handles.splice(i,1);
        }
      }
    }
  }  
} let p1 = new Pubsub();
p1.on('detail', (name)=> {console.log(name)});
p1.emit('detail', 'observer')
let p2 = new Pubsub();
p2.on('detail', (name)=> {console.log(name)});
p2.emit('detail', 'observer2')
p2.off('detail');
p2.emit('detail', 'observer3');

转自 https://segmentfault.com/a/1190000012430769

最新文章

  1. [译] Paxos算法详解
  2. apache通过cgi调用exe程序
  3. linux grep
  4. 别老扯什么Hadoop了,你的数据根本不够大
  5. [知识库分享系列] 二、.NET(ASP.NET)
  6. 非线性数据拟合-nls
  7. leetcode 92 Reverse Linked List II ----- java
  8. 史上最佳 Mac+PhpStorm+XAMPP+Xdebug 集成开发和断点调试环境的配置
  9. 在应用程序中实现对NandFlash的操作
  10. idea开发工具中你可能不知道的却又比较好用的快捷键
  11. 深入理解java回调机制
  12. php使用iconv进行从utf-8转为gb2312字符编码出错或截断的解决方案
  13. docker容器自动退出的问题
  14. NOIP2012 提高组 Day 2
  15. BZOJ_3427_Poi2013 Bytecomputer_DP
  16. Hibernate 单向一对多映射
  17. [转] 简述js中 for in 与 for of 区别
  18. jemter模拟高并发访问(亲测ok)
  19. Python练习-一个怪癖老师的不可描述
  20. Any way to start Google Chrome in headless mode?

热门文章

  1. 流畅的python学习笔记:第十一章:抽象基类
  2. 用JavaScript判断一个对象是否数组?
  3. C ~ 指针零散记录
  4. LeetCode:子集 II【90】
  5. Java多线程系列 基础篇09 Object.wait/notifyJVM源码实现
  6. mini2440移植uboot 2011.03(下)
  7. POJ1113 Wall —— 凸包
  8. laravel基础课程---13、数据库基本操作2(lavarel数据库操作和tp对比)
  9. codeforces 558A A. Lala Land and Apple Trees(水题)
  10. bzoj2309 CTSC2011 字符串重排