您的位置:首页 > Web前端 > JavaScript

js设计模式 发布订阅模式

2019-04-14 10:18 405 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/JsongNeu/article/details/89293380

js设计模式 发布订阅模式

发布订阅模式

发布订阅模式中有一个注册中心,有订阅和发布方法,订阅者需要带着方法去订阅一个事件,当这个事件被发布时,订阅者执行这个方法

import _ from 'lodash';
// import { MntrCurrentDimension } from './mntr-current-dimension';

/*
* @Description: 注册中心
* @Author: jsong
* @LastEditors: jsong
* @Date: 2019-04-12 08:58:30
* @LastEditTime: 2019-04-14 10:11:24
*/
export class MntrPublish {
//   topics: {};
//   uid = -1;
//   dashBoardDimension: MntrCurrentDimension;

constructor() {
this.topics = {};
this.uid = -1;
}

// 订阅一个事件,把这个事件放到 全局的 对象中 用于 发布时调用
subscribe(event, func) {
if (!this.topics[event]) {
this.topics[event] = [];
}
this.topics[event].push({ token: ++this.uid, func: func });
}
// 发布 调用订阅时 的方法
publish(event, args = null) {
if (!this.topics[event]) {
return false;
}
const subscribers = this.topics[event];
let len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(args, event);
}
}

unsubscribe(token) {
for (const t in this.topics) {
if (this.topics[t]) {
_.pull(this.topics[t], ['tocken', token]);
}
}
}

//   set(dashBoardDimension: MntrCurrentDimension) {
//     this.dashBoardDimension = dashBoardDimension;
//     return this;
//   }
}
const publish = new MntrPublish();

publish.subscribe('event', () => console.log(' subscribe event '));

publish.publish('event');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: