concept

Observer mode: The observer mode is used when there is a one-to-many relationship between objects. For example, when an object is modified, it automatically notifies its dependent objects. Observer mode is a behavior mode

For example, addeventListener is the most common one

When we define a click event, if we use onClick as follows, the latter overrides the former

  document.onclick = function(){
     console.log('123')
  }
 document.onclick = function(){
  console.log('456')
}
Copy the code

But if we implement it with addEventListener, it will print everything

 document.addEventListener('click',()=>{
      console.log('123')
    })
    document.addEventListener('click',()=>{
      console.log('456')
    })
Copy the code

Next we’ll implement an observer pattern class ourselves

Class Event {events = {} /* Add Event handler */ on(eventName,fn){if(! this.events[eventName]){ this.events[eventName] = [] } if(! this.events[eventName].includes(fn)){ this.events[eventName].push(fn) } } off(eventName,fn){ if(! this.events[eventName]){ return } this.events[eventName] = this.events[eventName].filter(item=>item! ==fn)} // Event trigger dispatch(eventName,... arg){ if(! this.events[eventName]){ return } this.events[eventName].forEach(item => { item.call(this,... arg) }); }}Copy the code