Search code examples
javascriptfunctionargumentseventemitter

How do arguments in publish/subscribe pattern work?


In one place we use eventEmitter to generate events. Actually it's the very common way.

eventEmitter.emit('started', data, date);

In the other place we try to catch it. Everything is pretty clear when using arrow functions. 'data' and 'date' are passed to the function as arguments

someInstanse.event.on('started', (data, date) => {
    //crazy stuff here
})

But how this notaion in fact works? We determine 3 args with emitter and now we really have only event string and a function instead

someInstance.event.on('started', function(data, date) {
});

I suppose that before adding arrow functions it was the only way to call anonymous functions


Solution

  • This is the typical publish/subscribe design pattern. And it is really determined by how the emit and how subscribers respond to the event are implemented under the hood.

    Basically, in the publish function, you want to call every subscriber(on) functions, provided with the information with publish(emit). Below is just some pseudo-code.

    function publish(type, ...args) {
        // for each of the subscribers of that type
        for (let i = 0; i < pubsub[type].length; i++) {
            // you could do (this provides the listener with type)
            subscribers[i](type, ...args)
            // or you could do (the subscriber doesn't know the type)
            subscriber[i](...args)
        }
    }
    

    I wrote a minified pub/sub pattern in github, if you want to take a look. I think it's extremely helpful to help you understand this issue. https://github.com/thomasyimgit/pubsub/blob/master/index.js