/* Publish subscribe + There is an object that someone is watching + when the object changes, a third party notifies the person watching to trigger the skill + Example buy book 1. Ordinary program complain buy book = "go to the bookstore to ask did not go home =" after a while go again, ask, did not, go home 2. Subscription programmers = "go to the bookstore to buy a book, ask, no, leave a contact =" Once the book comes, Our task is to simulate an addEventListener() analysis constructor + property: message queue + method: can add content to message queue + method: Can delete message queue contents + Method: can trigger message queue contents */

class Observe{
    constructor() {
        this.message = {}
    }
    // Add content to the message queue
    on (type,fn) {
        // type the behavior of viewing
        // What fn does when the behavior occurs

        // Determine whether the behavior is registered
        // If the behavior is not assigned one by one, the value is assigned to [].
        // If so, add it directly to the array
        if (!this.message[type]) {
            this.message[type] = [fn]
        }else{
            this.message[type].push(fn)
        }
         
    }
    // Delete the contents of the message queue
    off (type,fn) {
        // Check whether there is a function
        if(! fn) {delete this.message[type]
            return 
        }
        if (!this.message[type]) return
        this.message[type] = this.message[type].filter(hand= > {returnhand! ==fn}) }// Triggers the message queue contents
    trigger(type) {
        if (!this.message[type]) return
        this.message[type].forEach(fn= > {
            fn()
        })
    }
}

// Use the constructor to create an instance
const person1 = new Observe()

// When you ask this person1 to observe something for you
// Tell you a behavior, when the behavior appears, tell you what to do

person1.on('abc',handler1)
person1.on('abc',handler2)
person1.on('hh',handler3)

// Tell person1 that you don't have to worry about this
// 1. I just told you that you don't have to worry about it
// 2. Remove the handlers below this event

person1.off('abc',handler1)

person1.trigger('hh')

function handler1 () {console.log(1)}
function handler2 () {console.log(2)}
function handler3 () {console.log(3)}

console.log(person1)
Copy the code