1. define

Also known as the observer pattern, it defines a one-to-many dependency between objects in which all dependent objects are notified when an object’s state changes

  1. The core

Instead of hard-coded notification between objects, one object no longer explicitly calls an interface of another object.

Unlike traditional publish-subscribe implementations, which pass the subscriber as a reference to the publisher, subscription is usually done in JS in the form of a registration callback function

  1. implementation

Events in JS are an implementation of the classic publish-subscribe pattern

/ / subscribe
document.body.addEventListener('click'.function() {
    console.log('click1');
}, false);

document.body.addEventListener('click'.function() {
    console.log('click2');
}, false);

/ / release
document.body.click(); // click1 click2
Copy the code

Let’s implement a simple publish-subscribe model for ourselves

/ / observer
var observer={
    subscribes: [].// Subscriber collection
    / / subscribe
    subscribe:function(fn){
        this.subscribes.push(fn)
    },
    / / release
    public(){
        this.subscribes.forEach(item= >{
            item.apply(this.arguments)})},// q unsubscribe
    remove(fn){
        for(let i=0,len=this.subscribes.length; i<len; i++){if(fn===this.subscribes[i]){
                this.subscribes.splice(i,1)}}}}let subscriber1=function(){
console.log("Subscribe object 1");
}
let subscriber2=function(){
console.log("Subscribe object 2");
}
let subscriber3=function(){
console.log("Subscribe object 3");
}
observer.subscribe(subscriber1)
observer.subscribe(subscriber2)
observer.subscribe(subscriber3)
setTimeout(() = > {
    observer.public();
}, 1000);
observer.remove(subscriber2)
// Finally output every one minute
// Subscribe to object 1
// Subscribe to object 3
Copy the code
  1. The advantages and disadvantages

advantages

One is the decoupling in time, and the other is the decoupling between objects. Can be used in asynchronous programming and MV* framework

disadvantages

Creating a subscriber itself takes time and memory, the subscription processing function is not necessarily executed, and resident memory has performance overhead

Weakened the relationship between objects, complex situations may lead to programs difficult to track maintenance and understanding