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:

  <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>
   window.addEventListener( "load", 

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.

  <h1>Retrieve and list all book records</h1>
  <table id="books">
  <a href="index.html">Back to main menu</a>

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 () {
    var tableBodyEl = document.querySelector("table#books>tbody");
    var keys=[], key="", row={}, i=0;
    // load all book objects
    keys = Object.keys( Book.instances);
    // for each book, create a table row with cells for the 3 attributes
    for (i=0; i < keys.length; i++) {
      key = keys[i];
      row = tableBodyEl.insertRow();
      row.insertCell(-1).textContent = Book.instances[key].isbn;      
      row.insertCell(-1).textContent = Book.instances[key].title;  
      row.insertCell(-1).textContent = Book.instances[key].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. Both insertRow and insertCell have to be invoked with the argument -1 for making sure that new elements are appended to the list of rows and cells.