This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging

  1. Understand what the observer mode is
  2. Understand what the publish-subscribe pattern is
  3. Understand what isqueueMicrotask()

This is the basic knowledge of Promise, let write a Promise become not difficult!! , which is the 0 to build the Promise

1. Observer mode

1.1 Basic Understanding

As shown in the figure [Schematic diagram of observer mode] :

Observer mode describes a one-to-many relationship, which simply means that a change in the state of an object triggers a response from different observers. In the illustrated Design Patterns, observer mode is one of the states managed

Following the diagram, we begin to implement an observer pattern

1.2 Implement a simple observer pattern example

  1. To create aObserverThe class of
  2. Creates a class to be observed
  3. The observed class needs to add a methodaddObserver, to collect instantiatedObserver
  4. State change, notification instantiatedObserver
// Create an Observer class
class Observer {
	constructor(name,action = ()=>{}) {
	    this.name = name;
		this.action = action
	}
	runAction(state){
		this.action(state,this.name)
	}
}
// Create a class to be observed
class Subject {
	constructor(name,state) {
	    this.name = name;
		this.nowState = state;
		
		this.oldState = null;
		this.obseverList = new Set(a); }// The observed class needs to add a method addObserver to collect the instantiated Observer
	addObserve(obsever){
		this.obseverList.add(obsever)
		return this
	}
	// State changes are notified to the instantiated Observer
	notifyObserve(state){
		this.nowState = state;
		if(this.oldState! = =this.nowState){
			for(let item of this.obseverList){
				item.runAction(this.nowState)
			}
			this.oldState = this.nowState
		}
		return this; }}const teacherA = new Observer(Teachers' A '.(state,name) = >{
	if(state === 'playing') {console.log( name+'Found you playing, call your parents.')}else if( state === 'studying') {console.log( name+'I praised you so much.')}})const teacherB = new Observer('the teacher B'.(state,name) = >{
	if(state === 'playing') {console.log( name+'Found playing, 30 minutes standing.')}})const deskmateA = new Observer('Ming'.(state,name) = >{
	if(state === 'eating') {console.log( name+'Noticed you were eating, so he started eating too.')}})const deskmateB = new Observer('the little f'.(state,name) = >{
	if(state === 'eating') {console.log( name+'Noticed you were eating, so he started eating too.')}})const You = new Subject('you'.'studying')
You.addObserve(deskmateA).addObserve(teacherA).addObserve(teacherB)
You.notifyObserve('playing')
You.notifyObserve('eating')
You.notifyObserve('studying')
Copy the code

Above is a very simple implementation of the observer pattern.

It is clear from this that the Subject and the individual observers are loosely coupled. When the state changes, the runAction that instantiates the Observer is called to execute the logic based on the state.

2 Publish and subscribe mode

2.1 Basic Understanding

The published-subscribe and observer patterns are, in general, similar (for example, Yudao thinks that the published-subscribe and observer patterns are the same). I’m not going to talk about the ideas of the big guys here, because we don’t control the code yet. But you can think of observer mode as analogous to publish/subscribe mode (Publisher in publish/subscribe mode is Subject in Observer mode, Subscriber, Observer), but a third party Observer is added in the publish/subscribe mode to forward, instead of the Subscriber directly notifies the state to the Publisher

On the front end, the fact that the browser is listening for events is a typical publish-subscribe pattern. . For example, the document addEventListener (‘ click ‘, () = > {}), the document is to monitor is the Publisher, ‘click’ on behalf of the published content Subject, at the back of the function of means, The subscription to this event is click and then we execute this function. If you follow this, you’ll be able to draw it

See figure [Publish-subscribe model] :

2.2 Implement a simple example of a publish-subscribe pattern

  1. Create a third-party observerObserverclass
  2. Give a third party observer oneaddEventListenerTo add a subscription to a message and a subscription to the messageSubscriberBehavior, but the thing to notice here is that there’s more than one messageSubscriberBehavior can be fixed, continue to addSubscriberThe behavior of the
  3. Give a third party observer oneremoveEventListenerYou can cancel a subscription. One is to cancel a single subscriptionSubscriberSubscribing to a message, and unsubscribing to a message directly
  4. Give a third party observer onenotifyMethod receivesPublisherIs triggeredSubscriberbehavior
class Observe {
	constructor() {
	    this.publisherMap = new Map(a); }/* * @param {String} type Type of the subscription message * @param {Function} ActionFn Action of the corresponding Subscriber, which is also the action of the target of the push message (Subscriber) **/
	addEventListener(type,actionfn){
		if( !actionfn ){
			console.error('Binding failed')}let actionfnList = new Set(a);if(this.publisherMap.has(type)){
			actionfnList = this.publisherMap.get(type)
		}
		actionfnList.add(actionfn)
		this.publisherMap.set(type,actionfnList)
	}
	// Unsubscribe from Publisher
	removeEventListener(type,actionfn){
		if( this.publisherMap.has(type) && actionfn){
			const actionfnList = this.publisherMap.get(type)
			if(actionfnList.size){
				actionfnList.delete(actionfn)
			}else{
				this.publisherMap.delete(type)
			}
		}else if( this.publisherMap.has(type) && ! actionfn){this.publisherMap.delete(type)
		}else{
			console.error('No queue for this message')}}// Triggers the Subscriber action, also called publishing a notification message
	notify(type){
		if(this.publisherMap.has(type)){
			const actionfnList = this.publisherMap.get(type)
			for(let subscriberAction of actionfnList){
				subscriberAction(this); }}}}// The teacher appoints a monitor to monitor your status
const monitor = new Observe()
const yourState = ['studying'.'eating']
const teacherAction = function(){
	console.log('I want to give you a lot of credit.')}const deskmeatAction = function(e){
	console.log('Eat together',e)
}
monitor.addEventListener(yourState[0],teacherAction)
monitor.addEventListener(yourState[0].() = >{
	console.log("Here's a big red flower.")
})
monitor.addEventListener(yourState[1],deskmeatAction)
monitor.notify(yourState[0])
monitor.notify(yourState[1])
Copy the code

As you can see, in the publis-subscribe pattern, publishers and subscribers are not loosely coupled, but completely decoupled. The connection between them is mediated by third-party observers. From a code implementation point of view, the necessary constructor only implements a third party Observer

The biggest difference between the publis-subscribe model and the observer model is that in the publis-subscribe model, the publisher does not inform the subscribers directly, in other words, the publisher and the subscriber do not know each other. This is also a feature of complete decoupling

3. What you don’t knowqueueMicrotask()

Use microtasks in JavaScript with queueMicrotask()

Instead of going into the depth of microtasks and macro tasks, I will simply say that tasks can be viewed as execution statements. Generally, it runs synchronously from top to bottom. When asynchronous events are encountered, they need to be pushed into the event circular queue. There are two kinds of event circular queue, one is microtask circular queue, the other is macro task circular queue. The microtask is executed before the macro task.

Simple use is as follows:

console.log('a')
window.queueMicrotask(() = >{
	console.log('b')})console.log('c')
Copy the code

With that in mind, handwritten promises will be much easier. No rote learning at all!!

The resources

  1. Observer pattern vs. publish/subscribe pattern H
  2. Graphic design pattern
  3. queueMicrotask