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

Summary of several error logs about MySQL MHA setup and switching

1: masterha_check_repl replica set error replicat...

Problems with nodejs + koa + typescript integration and automatic restart

Table of contents Version Notes Create a project ...

Ten popular rules for interface design

<br />This is an article I collected a long ...

React entry-level detailed notes

Table of contents 1. Basic understanding of React...

Vue implements time countdown function

This article example shares the specific code of ...

Reasons why MySQL kill cannot kill threads

Table of contents background Problem Description ...

MySQL InnoDB row_id boundary overflow verification method steps

background I talked to my classmates about a boun...

Detailed explanation of HTML basics (Part 2)

1. List The list ul container is loaded with a fo...

Front-end JavaScript operation principle

Table of contents 1. What is a JavaScript engine?...

Detailed analysis of MySQL optimization of like and = performance

introduction Most people who have used databases ...

MySQL 8.0.18 installation tutorial under Windows (illustration)

Download Download address: https://dev.mysql.com/...

Summarize the User-Agent of popular browsers

1. Basic knowledge: Http Header User-Agent User A...

How to delete node_modules and reinstall

Table of contents Step 1: Install node_modules in...

CSS uses calc() to obtain the current visible screen height

First, let's take a look at the relative leng...

How to check if a table exists in MySQL and then delete it in batches

1. I searched for a long time on the Internet but...