Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

84
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

7 months 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.

7 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos