5. Step 5 - Implement the Retrieve/List All Use Case

The user interface for the CRUD use case Retrieve consists of an HTML table for displaying the data of all model objects. For our example app, this page is called retrieveAndListAllBooks.html, located in the main folder MinimalApp, and it contains the following code in its head element:

<head>
  <meta charset="UTF-8" />
  <title>Simple JS Front-End App Example</title>
  <script src="src/c/initialize.js"></script>
  <script src="src/m/Book.js"></script>
  <script src="src/v/retrieveAndListAllBooks.js"></script>
  <script>
   window.addEventListener( "load", 
       pl.v.retrieveAndListAllBooks.setupUserInterface);
  </script>
</head>

Notice that, in addition to loading the app initialization JS file and the model class JS file, we load the view code file (here: retrieveAndListAllBooks.js) and invoke its setupUserInterface procedure via a load event listener. This is the pattern we use for all four CRUD use cases.

<body>
 <header>
  <h1>Retrieve and list all book records</h1>
 </header>
 <main>
  <table id="books">
   <thead><tr><th>ISBN</th><th>Title</th><th>Year</th></tr></thead>
   <tbody></tbody>
  </table>
 </main>
 <footer>
  <a href="index.html">Back to main menu</a>
 </footer>
</body>

In the setupUserInterface procedure, we first set up the data management context by retrieving all book data from the database and then fill the table by creating a table row for each book object from Book.instances:

 pl.v.retrieveAndListAllBooks = {
  setupUserInterface: function () {
    const tableBodyEl = document.querySelector("table#books>tbody");
    // load all book objects
    Book.retrieveAll();
    // for each book, create a table row with a cell for each attribute
    for (const key of Object.keys( Book.instances)) {
      const book = Book.instances[key];
      const row = tableBodyEl.insertRow();
      row.insertCell().textContent = book.isbn;
      row.insertCell().textContent = book.title;
      row.insertCell().textContent = book.year;
    }
};

More specifically, the procedure setupUserInterface creates the view table in a loop over all objects of Book.instances. In each step of this loop, a new row is created in the table body element with the help of the JavaScript DOM operation insertRow(), and then three cells are created in this row with the help of the DOM operation insertCell(): the first one for the isbn property value of the book object, and the second and third ones for its title and year property values.