javascript订阅模式浅析和基础实例

前言

最近在开发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订阅模式浅析和基础实例

欢迎关注公众号:程序员布欧,不定期更新一些前端入门文章

创作不易,转载请注明出处和作者。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
发布订阅模式又称观察者模式,是一种常见的设计模式,它定义了对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知。下面是手写JavaScript发布订阅模式的一种实现方式: ```javascript function PubSub() { this.subscribers = {}; } PubSub.prototype.subscribe = function(event, callback) { if (!this.subscribers[event]) { this.subscribers[event] = []; } this.subscribers[event].push(callback); }; PubSub.prototype.unsubscribe = function(event, callback) { if (!this.subscribers[event]) { return; } var index = this.subscribers[event].indexOf(callback); if (index > -1) { this.subscribers[event].splice(index, 1); } }; PubSub.prototype.publish = function(event, data) { if (!this.subscribers[event]) { return; } this.subscribers[event].forEach(function(callback) { callback(data); }); }; ``` 使用方式如下: ```javascript var pubsub = new PubSub(); function callback1(data) { console.log('callback1:', data); } pubsub.subscribe('event1', callback1); function callback2(data) { console.log('callback2:', data); } pubsub.subscribe('event2', callback2); pubsub.publish('event1', { message: 'hello' }); pubsub.publish('event2', { message: 'world' }); pubsub.unsubscribe('event1', callback1); pubsub.publish('event1', { message: 'hello again' }); ``` 输出结果为: ``` callback1: {message: "hello"} callback2: {message: "world"} ``` 当调用 `publish` 方法时,订阅了该事件的所有回调函数都将被执行,并且可以传递一个数据对象作为参数。调用 `subscribe` 方法注册一个回调函数,当该事件被发布时,该回调函数将被执行。调用 `unsubscribe` 方法取消订阅

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值