preface

The concept of an event bus may be unfamiliar to you, but when it comes to the observer (publish-subscribe) pattern, you probably are. The event bus is an implementation of the publish-subscribe pattern. It is a centralized event processing mechanism that allows different components to communicate with each other without relying on each other to achieve a decoupling purpose.

Let’s look at the flow of the event bus:

See here I know that some of you are still a little bit of a fool (in fact, I am a fool), it doesn’t matter, we take it step by step, no hurry

Nature of the event

Let’s first explore the concept of events.

As anyone who has developed WinForm knows, when we do UI design, we drag in a btnRegister button from the toolbox, double-click it, and VS automatically generates the following code for us:

Void btnRegister_Click(object sender, EventArgs e) {Copy the code

The object Sender refers to the object that emitted the event, in this case the button object; EventArgs e Event parameters, which can be interpreted as descriptions of events, can be collectively referred to as event sources. The logic of the code is the handling of events. We can collectively call this event handling.

So far, it has been consumed by An event handler and An event is raised by An event source.

Ok, now that the nature of the event is clear, let’s look at the publish subscribe model!

Publish and subscribe model

Define a one-to-many dependency between objects so that whenever an object changes state, all dependent objects are notified and automatically updated. Publish and subscribe

The publish subscribe model has two main roles:

  • Publisher: Also known as observed, responsible for notifying all subscribers when status changes.
  • Subscriber: also called observer, subscribes to events and processes the received events.

The publish subscribe model can be implemented in two ways:

  • Simple implementation: Publisher maintains a list of subscribers and loops through the list to notify subscribers when status changes.
  • Delegate implementation: Event delegate is defined by Publisher and Subscriber is implemented.

In general, there are two keywords in the publish-subscribe model, notifications and updates. The observed state changes and notifies the observer to update accordingly. It addresses the problem of notifying other objects when they change.

Dictation is complicated, let’s look at the picture!

All right, that’s all for starters, it’s time for dinner.

Event Bus (publish subscribe mode)

Class EventEmitter {constructor() {this.cache = {}} on(name, constructor) fn) { if (this.cache[name]) { this.cache[name].push(fn) } else { this.cache[name] = [fn] } } off(name, fn) { let tasks = this.cache[name] if (tasks) { const index = tasks.findIndex(f => f === fn || f.callback === fn) if (index >= 0) { tasks.splice(index, 1) } } } emit(name, once = false, ... Args) {if (this.cache[name]) {// Create a copy, if the same event continues to be registered in the callback function, Let tasks = this.cache[name].slice() for (let fn of tasks) {fn(... Args)} if (once) {delete this.cache[name]}}}} // Let eventBus = new eventBus () let fn1 = function(name, age) { console.log(`${name} ${age}`) } let fn2 = function(name, age) { console.log(`hello, ${name} ${age} ')} eventBus.on('aaa', fn1) eventbus. on('aaa', fn2) eventbus. on(' AAA ', fn2) eventbus. on(' AAA ', fn2) eventbus. emit('aaa', false, 'blank ', // 'Hello, Bran 12'Copy the code

So much look down, small partner is not very desperate ah, nothing nothing, we parse it!

  • Create a repository
Constructor () {// Create a data source this.cache = {}}Copy the code
  • Bind events:

on(name, fn) {}

The first step is to determine whether the current event exists, and if so, push fn into the data. [name]:[fn]

on(name, fn) {
        if (this.cache[name]) {
            this.cache[name].push(fn)
        } else {
            this.cache[name] = [fn]
        }
    }
Copy the code
  • Untying events:

off(name, fn) {}

The first step is to check whether the current event tasks exists, and then to check whether the second parameter exists. If so, remove fn or callback

 off(name, fn) {
        let tasks = this.cache[name]
        if (tasks) {
            const index = tasks.findIndex(f => f === fn || f.callback === fn)
            if (index >= 0) {
                tasks.splice(index, 1)
            }
        }
    }
Copy the code
  • Triggering event:

emit(name, once = false, ... args) {}

The first step is to check whether the current event exists. If there is an index in the traversal number group, call the function. If name exists, pass the function paramsc

emit(name, once = false, ... Args) {if (this.cache[name]) {// Create a copy, if the same event continues to be registered in the callback function, Let tasks = this.cache[name].slice() for (let fn of tasks) {fn(... args) // ... } if (once) {delete this.cache[name]}}}Copy the code

Tip:

Tasks =this.cache[name].slice() uses.slice() to return a subarray with all elements of cache[name] assigned to tasks

The slice() method returns selected elements from an existing array.

Grammar: arrayObject. Slice (start, end)

  • Start a necessity. Specify where to start. If it is negative, it specifies the position from the end of the array. That is, -1 is the last element, -2 is the next-to-last element, and so on.
  • The end is optional. Specify where to end the selection. This parameter is the array subscript at the end of the array fragment. If this parameter is not specified, the shard array contains all elements from start to the end of the array. If this parameter is negative, it specifies the element from the end of the array.
  • Return value Returns a new array containing elements from the arrayObject from start to end (excluding the element).

Note:

This method does not modify the array, but returns a subarray. If you want to delete an element from an Array, use the array.splice () method.

conclusion

Explain so much, the following test on their own to try to push it, in fact, very simple, after all, learning is their own thing, don’t be ashamed, friends, refueling refueling, I believe you, refueling.