The publisher subscriber pattern has one more layer of event scheduling center than the observer pattern. The main release events, triggering events, delete events and other functions.

ES5 prototype writing

function EventBus() {
            // Define an event container
            this.eventList = {};

            // Add event method. Parameters include event name and event method
            EventBus.prototype.listen = function (event, callback) {
                // Create a new event container
                if(! (eventin this.eventList)) {
                    this.eventList[event] = []
                };
                this.eventList[event].push(callback);
            }

            // Trigger the event with two parameters (event name, parameters)
            EventBus.prototype.emit = function (event, ... args) {
                // An error is thrown if no event is registered
                if(! (eventin this.eventList)) {
                    throw new Error('Unregistered Event')}// Trigger the event
                this.eventList[event].forEach(fn= >{ fn(... args) }); }// Remove the event (delete the subscription and publish of the event without the second argument)
            EventBus.prototype.delete = function (event, callback) {
                if (!this.eventList[event]) {
                    throw new Error('Invalid event')}if (this.eventList[event]) {
                    let index = this.eventList[event].indexOf(callback)
                    // There are callback methods, delete methods
                    if(index ! = = -1) {
                        this.eventList[event].splice(index, 1)}// Delete events without callback methods
                    if (arguments.length === 1) {
                        delete this.eventList[event]
                    }
                }
            }
        }
Copy the code

test

let a = new EventBus();
        let foo1 = function (msg) {
            console.log(msg);
        }
        let foo2 = function (msg) {
            console.log('fsaf');
        }
        let foo3 = function (a) {
            console.log('1111');
        }

        a.listen('sayHi', foo1)
        a.listen('haha', foo2)
        a.listen('sayHi', foo3)


        a.emit('sayHi'.Math.random())
        a.emit('sayHi'['214214'.'12312'])
        a.emit('haha'.1241)

        a.delete('sayHi', foo3)


        console.log(` # # # # # # # # # # # # # # # # # # # # # # # # # # # # `)

        a.emit('sayHi'.Math.random())
        a.emit('sayHi'['214214'.'12312'])
        a.emit('haha'.1241)
Copy the code


Record the record!