Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

355
Visualizações
why is my PubSub pattern not working as intended

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>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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;
    }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda