使用JavaScript怎么实现一个发布订阅功能

发布时间:2021-01-25 16:06:06 作者:Leah
来源:亿速云 阅读:125

今天就跟大家聊聊有关使用JavaScript怎么实现一个发布订阅功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

使用场景

异步通信、多页面间相互通信,pageA 的方法想在 pageB的方法调用的某个时机触发

直接上代码

class Publish {
 constructor() {
  this.listMap = {};
 }
	// 订阅
 on(key, fn) {
  this.listMap[key]
   ? this.listMap[key].push(fn)
   : this.listMap[key] = [fn];
   
		// 存储订阅fn的下标
  const index = this.listMap[key].length - 1;
  
		// 返回取消订阅的function
  return () => this.clear(key, index);
 }
 
	// 取消所有该key订阅
 off(key) {
  delete this.listMap[key];
 }
 
	// 取消key的指定的某个订阅
 clear(key, index) {
  index === this.listMap[key].length - 1
   ? this.listMap[key].pop()
   : this.listMap[key][index] = null;
 }
 
	//订阅一次触发后自动取消订阅
 once(key, fn) {
  this.on(key, (...rest) => {
   fn(...rest);
   this.off(key);
  });
 }

	// 发布key
 trigger(key, ...rest) {
 	if(key in this.listMap) {
	 	this.listMap[key].forEach(fn => {
	   fn(...rest);
	  });
 	}
 }
}

使用方法

const ob = new Publish();

// 订阅 sub1
const sub1 = ob.on('sub1', (a, b) => {
 console.log('sub1', a, b);
});

// 订阅 sub1
const sub11 = ob.on('sub1', (a, b) => {
 console.log('sub11', a, b);
});

ob.trigger('sub1', 2, 3);

// 取消订阅sub1
sub1();

// 取消订阅sub11
sub11();

// 订阅 sub3
ob.on('sub3', (a, b) => {
 console.log('sub3', a, b);
});

// 订阅 sub3
ob.on('sub3', (a, b) => {
 console.log('sub33', a, b);
});

ob.trigger('sub3', 6, 7);

// 取消订阅所有的sub3
ob.off('sub3');

// 订阅一次就自行取消订阅
ob.once('sub4', (a, b) => {
 console.log('sub4', a, b);
});

ob.trigger('sub4', 8, 9);

看完上述内容,你们对使用JavaScript怎么实现一个发布订阅功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. redis发布订阅功能介绍
  2. redis发布订阅功能怎么实现

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javascript

上一篇:怎么在mybatis中使用update对字段进行更新

下一篇:JavaScript中实现循环遍历数组的方法有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》