js Simple and Rough Publish Subscription Sample Code

  • 2021-10-24 18:48:59
  • OfStack

What is publish/subscribe?

For example, when you go to a store to buy clothes, you and the store manager don't know each other. The store manager only sells his clothes and doesn't care who buys them, while you just buy the clothes you want and don't care which store is selling them. At this time, the store and you form a publish/subscribe relationship.

When the store hangs out the clothes style, you go to find the clothes you want. If you find them, buy them. If you don't find them, leave the store. The whole process is as simple as that.

Usage scenario

Asynchronous communication, communication between multiple pages, pageA method wants to trigger at a certain time when pageB method calls

Direct code


class Publish {
 constructor() {
  this.listMap = {};
 }
	//  Subscribe 
 on(key, fn) {
  this.listMap[key]
   ? this.listMap[key].push(fn)
   : this.listMap[key] = [fn];
   
		//  Storage subscription fn Subscript of 
  const index = this.listMap[key].length - 1;
  
		//  Returns the unsubscribed function
  return () => this.clear(key, index);
 }
 
	//  Cancel all the key Subscribe 
 off(key) {
  delete this.listMap[key];
 }
 
	//  Cancel key A subscription specified by the 
 clear(key, index) {
  index === this.listMap[key].length - 1
   ? this.listMap[key].pop()
   : this.listMap[key][index] = null;
 }
 
	// Subscribe 1 Automatically unsubscribe after the second trigger 
 once(key, fn) {
  this.on(key, (...rest) => {
   fn(...rest);
   this.off(key);
  });
 }

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

Usage


const ob = new Publish();

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

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

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

//  Unsubscribe sub1
sub1();

//  Unsubscribe sub11
sub11();

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

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

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

//  Unsubscribe from all sub3
ob.off('sub3');

//  Subscribe 1 Unsubscribe yourself once 
ob.once('sub4', (a, b) => {
 console.log('sub4', a, b);
});

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

Summarize


Related articles: