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

Complete Tutorial on Deploying Java Web Project on Linux Server

Most of this article refers to other tutorials on...

Solution for using Baidu share on Https page

Since enabling https access for the entire site, ...

Pure HTML and CSS to achieve JD carousel effect

The JD carousel was implemented using pure HTML a...

Modification of the default source sources.list file of ubuntu20.04 LTS system

If you accidentally modify the source.list conten...

js dynamically implements table addition and deletion operations

This article example shares the specific code for...

Common array operations in JavaScript

Table of contents 1. concat() 2. join() 3. push()...

Vue/react single page application back without refresh solution

Table of contents introduction Why bother? Commun...

Introduction and use of triggers and cursors in MySQL

Trigger Introduction A trigger is a special store...

...

SQL fuzzy query report: ORA-00909: invalid number of parameters solution

When using Oracle database for fuzzy query, The c...

Record the steps of using mqtt server to realize instant communication in vue

MQTT Protocol MQTT (Message Queuing Telemetry Tra...

Two ways to manage volumes in Docker

In the previous article, I introduced the basic k...