JavaScript event publish/subscribe

1. The publish/subscribe model is also one of many design patterns;

2. In this way, asynchronous operations can be handled fairly elegantly under es5;

3. What is publish/subscribe? Let's give a chestnut:

Assuming that fn1, fn2, and fn3 can all be regarded as the publisher of an event, an event will be published when it is executed. At this time, we can subscribe to and process these events in batches through an event subscriber, including their order. How to add a message subscriber:

class AsyncFunArr {
  constructor (...arr) {
    this.funcArr = [...arr]
  }

  next () {
    const fn = this.funcArr.shift()
    if (typeof fn === 'function') fn()
  }

  run () {
    this.next()
  }
}

4. Call

//首先将fn1,fn2,fn3订阅
const asyncFunArr = new AsyncFunArr(fn1, fn2, fn3)

//fn1,fn2,fn3作为分布者分别调用其next()方法:
function fn1 () {
  console.log('Function 1')
  asyncFunArr.next()
}

function fn2 () {
  setTimeout(() => {
    console.log('Function 2')
    asyncFunArr.next()
  }, 500)
}

function fn3 () {
  console.log('Function 3')
  asyncFunArr.next()
}

5. Output:

// Function 1
// Function 2

// Function 3

6. Summary:

Through the above methods, many things can be achieved, such as asynchronously requesting data.

7. Reference materials: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor

Guess you like

Origin blog.csdn.net/joyksk/article/details/80902601