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

201
Visualizações
Why my function i event listener can't be called again after initial calling?

I have the following code:

HTML

 <button>Add Name</button>
 <ul id="names"></ul>

JS

class NameField {
    constructor(name) {
        const field = document.createElement('li');
        field.textContent = name;
        const nameListHook = document.querySelector('#names');
        nameListHook.appendChild(field);
    }
}

class NameGenerator {
    constructor() {
        const btn = document.querySelector('button');
        btn.addEventListener('click', this.addName);
    }

    addName() {
        const name = new NameField("Max");
    }
}

const gen = new NameGenerator();

so here when i click on the button, then every time the function addName gets executed and max is printed in the HTML.

But when i change the line to:

 btn.addEventListener('click', this.addName());

then i get initially printed Max on the browser HTML which is expected because i call the function immediately, i did not ommited the ().

But i don't understand why after the iniitial printing,when i click on the button i don't get printed Max again ? why is that ?

Okay i got initial printing on HTML, but should not i get printed now again Max when i click on the button ? And why am i not getting ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is because you have to hand over a reference to a function.
If you write

 btn.addEventListener('click', this.addName());

javascript calls this.addName() instantly and executes the return value of this.addName() when you click the button.

But this.addName() has no explicit return value, so it returns the standard Javascript return value, which is undefined.

So essentially what your code does is

btn.addEventListener('click', undefined);

except that this undefined is returned from your call to this.addName() (which runs the function once, hence you see the console output).

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