vendredi 23 juillet 2021

How a javascript pubsub/observer sees the function of another object?

I have this simple code, while trying to learn the basics of implementing the pubsub method in javascript.

people object emits a simple event and events object is the pubsub, takes the event and emits it to all that listen

Then stats that listens for that event, executes a function, with the data that came from the pubsub.

<html>
<h1>hello</h1>
<script>                    

    var events = {
        events:{},
        on:function(eventName, fn){
            this.events[eventName] = this.events[eventName] || [];
            this.events[eventName].push(fn);
        },
        emit:function (eventName, data) {
            if (this.events[eventName]) {
                this.events[eventName].forEach(function(fn){ 
                    console.log('events this ', this);
                    fn(data)
                });
            }
        }
    } 

    var stats = (function(){ 
        var counterstats = 0  
        events.on('peoplechange', setPeople);
        function setPeople(a) { 
            console.log('stats this ', this);
            counterstats++;
            console.log('stats people ', a )
        }
        
    })(); 

    var people = (function(){ 
        console.log('people this ', this);
        events.emit('peoplechange', 5);
    })();  
</script>
</html>

I am asking, how events knows and communicates with setPeople that is inside stats. setPeople is a method of an object, not exposed.

How events sees it? I thought I had to do events.on('peoplechange', events.setPeople); so events knows where this method belongs to.

I print the this of the function in the emit, and the this of the setPeople in the stats and they all point to Window.

I still cannot explain how events sees setPeople inside the stats, without specifying further.

Any explanation would be great. Apologies for asking basic things

Aucun commentaire:

Enregistrer un commentaire