why is my PubSub pattern not working as intended

135 views Asked by At

Please I am a bit confused why my code is not working.

I am trying to practice PubSub design pattern using the code below. The class instance displayGreet is subscribed to the messaged event published by the message function. The message function is the handler for the click event attached to the button.

The goal is to get the message function to send a message to displayGreet when the button is clicked so that the greeting is updated to the browser.

I was able to achieve the desired outcome when both the displayGreet and message were written as functions. But I am unable to achieve same when displaygreet is an instance of a class.

Please help me out.

class Pubsub {
    constructor() {
        this.subscribers = {};
    }

    subscribe(event, callback) {
        if (!this.subscribers[event]) {
            this.subscribers[event] = [];
        }
        this.subscribers[event].push(callback);
    }

    publisher(event, data) {
        if (!this.subscribers[event]) {
            return;
        }
        this.subscribers[event].forEach((callback) => {
            callback(data);
        });
    }
}
const pubsub = new Pubsub();
class Sub {
    constructor(pubsub) {
        this.pubsub = pubsub;
    }
    greet(greeting) {
        console.log(greeting);
        const paragraph = document.querySelector('.show')
        paragraph.textContent = greeting;
        this.pubsub.subscribe("greeted", greeting);
    }
}
const displayGreet = new Sub(pubsub);


function morning() {
    const greeting = "good morning";
    pubsub.publisher("greeted", greeting);
    return greeting;
}


const button = document.querySelector('.submit')
button.addEventListener('click', morning)
<!DOCTYPE html>
<html>

<head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
</head>

<body>
    <div id="app">
        <p class="show"></p>
        <button class="submit">submit</button>
    </div>

    <script src="src/index.js">
    </script>
</body>

</html>
1

There are 1 answers

3
Jessie On

You're never subscribing to the PubSub instance. Also, subscribe() is expecting a callback, which must be a regular function. So you can't say this since that's a class instance. Use this.greet instead.

class Sub {
    constructor(pubsub) {
        this.pubsub = pubsub;

        // Subscribe and call `this.greet`
        this.pubsub.subscribe("greeted", this.greet);
    }

    greet(greeting) {
        console.log(greeting);
        const paragraph = document.querySelector('.show')
        paragraph.textContent = greeting;
    }
}