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

163
Visualizações
how do you assign a dictionary of functions to javascript addeventlistener?

I'm using this book to learn javascript: Secrets of the JavaScript Ninja, Second Edition.

In the book, there is code to store functions in a dictionary as a way to manage multiple functions in an event handler.

var store = {
        nextId: 1,
        cache: {},
        add: function(fn){
            if (!fn.id) {
                fn.id = this.nextId++;
                this.cache[fn.id] = fn;
                return true;
            }
        }
    }
store.add(myFunction1);
store.add(myFunction2);
store.add(myFunction3);

But the book doesn't explain how to assign these functions to an event handler once they are stored the the dictionary store.cache.

So my question is, how does one assign these functions, straight from the dictionary, into the addEventListener function? I tried pulling the functions out individually, such as store.cache[1].name, but then an error pops up saying the parameter is not of type 'Object.' I also tried to use a loop to get the function names, but the names come back as strings and the event listener doesn't call the functions when the names are strings. What am I missing here? Thank you in advance!

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

0

You can refer to them by their numerical order in the array. Then still pass any parameters as needed.

let myFunction1 = function(p) {
  console.log(p)
}
var store = {
  nextId: 1,
  cache: {},
  add: function(fn) {
    if (!fn.id) {
      fn.id = this.nextId++;
      this.cache[fn.id] = fn;
      return true;
    }
  }
}
store.add(myFunction1);


store.cache[1]("x");

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