js simple and crude publish and subscribe sample code

js simple and crude publish and subscribe sample code

What is Publish/Subscribe?

Let me give you an example. 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. You only 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 puts out clothing styles, you go look for the clothes you want. If you find them, you buy them. If you don't find them, you leave the store. The whole process is that simple.

Usage scenarios

Asynchronous communication, communication between multiple pages, pageA's method wants to be triggered at a certain time when pageB's method is called

Directly on the code

class Publish {
 constructor() {
  this.listMap = {};
 }
	// Subscribe on(key, fn) {
  this.listMap[key]
   ? this.listMap[key].push(fn)
   : this.listMap[key] = [fn];
   
		//Store the subscript of subscription fn const index = this.listMap[key].length - 1;
  
		// Return the unsubscribe function
  return () => this.clear(key, index);
 }
 
	// Cancel all subscriptions to this key off(key) {
  delete this.listMap[key];
 }
 
	// Cancel a subscription specified by key clear(key, index) {
  index === this.listMap[key].length - 1
   ? this.listMap[key].pop()
   : this.listMap[key][index] = null;
 }
 
	//Subscribe once and automatically unsubscribe after triggering 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);
	  });
 	}
 }
}

How to use

const ob = new Publish();

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

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

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

// Unsubscribe from sub1
sub1();

// Unsubscribe from sub11
sub11();

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

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

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

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

// Subscribe once and unsubscribe automatically ob.once('sub4', (a, b) => {
 console.log('sub4', a, b);
});

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

Summarize

This is the end of this article about the simple and crude publishing and subscription of js. For more relevant js simple publishing and subscription content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript Design Patterns: Observer Pattern (Publisher-Subscriber Pattern)
  • JS mode of simple subscriber and publisher mode complete example
  • A simple example of the publish/subscribe pattern in JavaScript
  • Analysis of the principles and usage of JavaScript event publishing/subscribing model
  • Detailed explanation of JavaScript implementation and use of publish/subscribe mode
  • Example explanation of js publish-subscribe mode
  • Simple example of subscription publisher mode implemented in js
  • JavaScript design pattern observer mode (publish and subscribe mode) principle and implementation method example
  • [JS Master Road] Design Pattern Series Courses - Examples of Publishers and Subscribers Refactoring Shopping Carts
  • Detailed examples of proxy mode and subscription publishing mode in js design pattern

<<:  Docker installation method and detailed explanation of Docker's four network modes

>>:  MySQL 5.7.10 Installation Documentation Tutorial

Recommend

Implementation of local migration of docker images

I've been learning Docker recently, and I oft...

Detailed explanation of DIV+CSS naming rules can help achieve SEO optimization

1. CSS file naming conventions Suggestion: Use le...

An article to understand the advanced features of K8S

Table of contents K8S Advanced Features Advanced ...

How to delete extra kernels in Ubuntu

Step 1: View the current kernel rew $ uname -a Li...

Html+css to achieve pure text and buttons with icons

This article summarizes the implementation method...

How to allow external network access to mysql and modify mysql account password

The root account of mysql, I usually use localhos...

How to use axios to filter multiple repeated requests in a project

Table of contents 1. Introduction: In this case, ...

How to load third-party component libraries on demand in Vue3

Preface Take Element Plus as an example to config...

React implements paging effect

This article shares the specific code for React t...

Solution to Linux server graphics card crash

When the resolution of the login interface is par...

RGB color table collection

RGB color table color English name RGB 16 colors ...