Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

344
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda