This series also does not have any tricks, is to complete the usual interview some handwriting functions, test these simple implementation of the advantage is that you can see the basic coding level, and take a short time, a more comprehensive view of your code strength. Generally, there are not many boundary conditions, so that the interview time is not enough, the investigation is not comprehensive.

If you don’t know or are not clear about the API, just ask the interviewer directly, how to use the API under Google anyone can immediately understand the knowledge also can’t see the level. The key is in the implementation process, and your coding status, habits, clarity of thought and so on.

Note that it is a simple implementation, not a complete implementation, it is important to clear the concept and clear implementation ideas, it is suggested to explain the concept first => write use cases => write pseudo-code => then realize specific functions, and then optimize, step by step.

24. Handwritten publish and subscribe model

What is the

It’s like a magazine subscription

If you subscribe to a magazine from EventEmitter, you don’t have to keep going to the publisher to see if a new book is coming out. The newsstand will send the issue directly to your home after publication (emit) and you can read it (go to the callback to execute the events you subscribe to)

You can also unsubscribe (off)

It’s the observer model in a very broad sense

The difference is

  • Observer mode: The data source directly notifies the observer of changes.
  • Publish subscribe mode: The data source tells the third party (event channel) that the change has occurred, and the third party notifies the subscriber of the change.

In fact, I think it’s the business focus,

  • One is concerned about changes in the data source, and I observe them directly, such as vue’s bidirectional binding, where data changes and the view must change as well.
  • One is event messages, I don’t care where the data comes from, I don’t care about changes, I just subscribe to one or more event messages in a center and notify me when something happens. (As long as anyone sends such an event or message, I will deal with it accordingly)

Wiki: In a publish/subscribe system, publishers publish messages to an intermediary broker, and subscribers register subscriptions with the broker, which filters them. Message brokers typically perform store-and-forward functions to send messages from publishers to subscribers.

After a general understanding of our simple implementation

Handwritten implementation

In fact, most problems, if you really understand the use of this thing, you can write the right use case

The test case

// Start with a new central instance
let em = new EventEmitter();

// Define two callback functions to be fired at the notification subscriber
function user1Callback (cbName) {
    console.log('User 1 subscribes to :', cbName);
}

function user2Callback (cbName) {
    console.log('User 2 subscribes to :', cbName);
}

// Subscriber user 1 and user 2 both subscribe to magazineEvent1
em.on('magazineEvent1', user1Callback);
em.on('magazineEvent1', user2Callback);

em.emit('magazineEvent1'.'Publish and subscribe');
// Event triggers notify all subscribers, so print:
// User 1 subscribes to publish-subscribe mode
// User 2 subscribes to publish-subscribe mode

em.off('magazineEvent1', user1Callback);
// User one unsubscribes
em.emit('magazineEvent1'.'Publish and subscribe');
// Only user 2 can receive it this time
// User 2 subscribes to publish-subscribe mode

em.once('magazineEvent2', user1Callback).emit('magazineEvent2'.'Book Two for the first time')
// Enable chained calls, user 1 subscribes once subscribe to the second magazine magazineEvent2, print:
// User 1 subscribed to: second book once
em.emit('magazineEvent2'.'The second book the second time')
// Since it is a single subscription, it will not trigger
Copy the code

So with this example, we know what’s going on. The implementation steps are clear from the comments

// Publish subscribe mode
class EventEmitter {
    constructor() {
        // Store the name and event of the subscription
        this.events = {};
    }

    // A method to subscribe to events
    on(eventName, callback) {
       if (!this.events[eventName]) {
           // Note that a name can subscribe to multiple event functions, so it is an array
           this.events[eventName] = [callback]
       } else  {
           this.events[eventName].push(callback)
       }
       // The chain call returns this
       return this
    }

    // The method that triggers the event
    emit(eventName, ... rest) {
        // Iterate over events that execute all subscriptions
        if (this.events[eventName]) {
            this.events[eventName].forEach( callback= >  callback.apply(this, rest));
        }
        return this
    }

    // Remove subscription events
    off(eventName, callback) {
        if (this.events[eventName]) {
            this.events[eventName] = this.events[eventName].filter(cb= >cb ! = callback) }return this
    }

    // Execute subscribed events only once, then remove
    once(eventName, callback) {
        let fn = (. rest) = > {
            // Execute once
            callback.apply(this, rest); 
            // Unsubscribe once executed
            this.off(eventName, fn); 
        }
        // Fn is fired when the subscription executes
        this.on(eventName, fn)
        return this}}let em = new EventEmitter();

function user1Callback (cbName) {
    console.log('User 1 subscribes to :', cbName);
}
function user2Callback (cbName) {
    console.log('User 2 subscribes to :', cbName);
}

em.on('magazineEvent1', user1Callback).on('magazineEvent1', user2Callback)
em.emit('magazineEvent1'.'Publish and subscribe');


em.off('magazineEvent1', user1Callback).emit('magazineEvent1'.'Publish and subscribe');


em.once('magazineEvent2', user1Callback).emit('magazineEvent2'.'Book Two for the first time')
em.emit('magazineEvent2'.'The second book the second time')


// User 1 subscribes to publish-subscribe mode
// User 2 subscribes to publish-subscribe mode
// User 2 subscribes to publish-subscribe mode
// User 1 subscribed to: second book first time
Copy the code

That’s all for today

In addition, we recommend another series of articles, very simple, on the front of the advanced students are very effective, wall crack recommended!! Core concepts and algorithms disassembly series remember to like ha

If you want to brush the questions with me, you can add me on wechat. Click here to make a friend Or search my wechat account, infinity_9368. You can chat with me and add my secret code “Tianwang Gaidihu”. Verify the message please send me Presious tower shock the rever Monster, I see it through, after adding I will do my best to help you, but pay attention to the way of asking questions, it is suggested to read this article: the wisdom of asking questions

reference