最近在开发redux或者vux的时候,状态管理当中的createStore,以及我们在组件中调用的dispatch传递消息给状态管理中心,去处理一些操作的时候,有些类似我们常见到订阅模式
于是写了一个小demo去实现了一下订阅模式的过程
订阅模式类似某个平台的作者,或者UP主,而平台充当了一个中间件传递消息的作用,作者是发布订阅的人,在被关注或者订阅了之后,发布的消息,收听作者的用户,可以收到作者发布的消息
var Messege = function () { this.list = {}; this.cache = {};};Messege.prototype.add = function (noticeType, client) { // 将收到的信息加入到noticeType订阅列表当中 console.log(noticeType); console.log(client); if (!this.list[noticeType]) this.list[noticeType] = []; this.list[noticeType].push(client); this.cache[noticeType].forEach((words) => { client.listen(noticeType, words); });};// 通过传入的信息类型,遍历查找Messege.prototype.remove = function (noticeType, client) { if (!this.list[noticeType]) return; //可以作为提示或者说处理符合业务需求的操作 var index = this.list[noticeType].findIndex((item) => item === client); console.log(this.list[noticeType].splice(index, 1)); this.list[noticeType].splice(index, 1);};在发布了这些往期列表当中,以及订阅了up主的订阅者,可以通过往期消息查看以前发布过的文章信息列表
Messege.prototype.triggle = function (noticeType, words) { if (!this.cache[noticeType]) this.cache[noticeType] = []; this.cache[noticeType].push(words); if (!this.list[noticeType]) return; this.list[noticeType].forEach((client) => { client.listen(noticeType, words); });};var Client = function (name) { this.name = name;};// 监听事件,事件处理逻辑Client.prototype.listen = function (noticeType, words) { console.log(`${this.name}收到${noticeType}的信息是:${words}`);};<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>订阅模式</title></head><body></body><script src="./subscribe.js"></script><script> var client1 = new Client('client1') var client2 = new Client('client2') var messege = new Messege() // messege.add('新消息01', client1) // messege.remove('新消息01', client1) messege.triggle('新消息02', "这是一段消息01"); messege.triggle('新消息02', "这是一段消息02"); var client3 = new Client('client3'); messege.add('新消息03', client3); messege.add('新消息03', client3); messege.remove('新消息03', client3);</script></html>通过实例化对象,实例化订阅信息之后,可以实现页面或者组件之间,相应的一些状态更改和数据之间的传递。
以上是javascript订阅模式的浅析
源码地址:
// githup仓库地址https://github.com/akari16/FunctionRealization文章个人博客地址:javascript订阅模式浅析和基础实例,欢迎订阅