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

347
Visualizações
How to change the contents of a class construcor in a javascript class and access it later?

Edit: I have a demo here

I want to fetch data from an API, add it to the constructor of a class, and then on button Click display it to the page.

class Entry {
  constructor() {
    this.pages = [];
  }
  loadAllEntries(url) {
    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        this.pages = data;
        // this would do it autuomatically, it's not what I want
        //this.displayAllEntries("#notes-list");
      });
  }

  displayAllEntries(node) {
    let ul = document.createElement("ul");
    ul.id = "display-list-note";
    this.pages.map((page) => { 
      let li = document.createElement("li");
      li.innerText = page.title;
      ul.appendChild(this.createClickableItem(page));
    });
    document.querySelector(node).appendChild(ul);
  }
  createClickableItem(item) {
    let li = document.createElement("li");
    li.innerText = item.title;
    li.addEventListener("click", () => {
        console.log(item.id);
    });
    return li;
  }
}

const courses = new Entry();
courses.loadAllEntries("http://localhost:1338/courses?favorite=true");

// on some click I want to run 

courses.displayAllEntries("#notes-list");

But, displayAllEntries acts as if loadAllEntries never ran!

later on I want to do something like courses.deleteEntry(213) and change the contents of the constructor, (a glorified todo list type of thing)

Edit: I have a demo here

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The smallest touch that will fix this is as follows:

  1. return the promise from the fetch
    loadAllEntries(url) {
      // just return, no further changes required
      return fetch(url)
        .then(...
  1. At the top level, carry on after the fetch is done with then
const courses = new Entry();
const url = "http://localhost:1338/courses?favorite=true";
courses.loadAllEntries(url).then(() => {
  courses.displayAllEntries("#notes-list");
});

If the underlying methods work, this will work.

about 4 years ago · Santiago Trujillo 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