js 实现发布订阅模式
2024-08-29 14:13:06
/* 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
最新文章
- [译] Paxos算法详解
- apache通过cgi调用exe程序
- linux grep
- 别老扯什么Hadoop了,你的数据根本不够大
- [知识库分享系列] 二、.NET(ASP.NET)
- 非线性数据拟合-nls
- leetcode 92 Reverse Linked List II ----- java
- 史上最佳 Mac+PhpStorm+XAMPP+Xdebug 集成开发和断点调试环境的配置
- 在应用程序中实现对NandFlash的操作
- idea开发工具中你可能不知道的却又比较好用的快捷键
- 深入理解java回调机制
- php使用iconv进行从utf-8转为gb2312字符编码出错或截断的解决方案
- docker容器自动退出的问题
- NOIP2012 提高组 Day 2
- BZOJ_3427_Poi2013 Bytecomputer_DP
- Hibernate 单向一对多映射
- [转] 简述js中 for in 与 for of 区别
- jemter模拟高并发访问(亲测ok)
- Python练习-一个怪癖老师的不可描述
- Any way to start Google Chrome in headless mode?
热门文章
- 流畅的python学习笔记:第十一章:抽象基类
- 用JavaScript判断一个对象是否数组?
- C ~ 指针零散记录
- LeetCode:子集 II【90】
- Java多线程系列 基础篇09 Object.wait/notifyJVM源码实现
- mini2440移植uboot 2011.03(下)
- POJ1113 Wall —— 凸包
- laravel基础课程---13、数据库基本操作2(lavarel数据库操作和tp对比)
- codeforces 558A A. Lala Land and Apple Trees(水题)
- bzoj2309 CTSC2011 字符串重排