4. Step 4 - Implement the Create Use Case

For our example app, the user interface page for the CRUD use case Create is called createBook.html located in the MinimalApp folder. In its head element, it loads the app initialization file initialize.js, the model class file Book.js and the view code file createBook.js, and adds a load event listener for setting up the Create user interface:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Minimal JS Front-End App Example</title>    
  <script src="src/c/initialize.js"></script>
  <script src="src/m/Book.js"></script>
  <script src="src/v/createBook.js"></script>
  <script>
   window.addEventListener("load", 
       pl.v.createBook.setupUserInterface);
  </script>
</head>
<body>...</body>
</html>

For a data management use case with user input, such as "Create", an HTML form is required as a user interface. The form typically has a labelled input or select field for each attribute of the model class:

<body>
 <header>
  <h1>Create a new book record</h1>
 </header>
 <main>
  <form id="Book">
   <div><label>ISBN: <input name="isbn" /></label></div>
   <div><label>Title: <input name="title" /></label></div>
   <div><label>Year: <input name="year" /></label></div>
   <div><button type="button" name="commit">Save</button></div>
  </form>
 </main>
 <footer>
  <a href="index.html">Back to main menu</a>
 </footer>
</body>

The view code file src/v/createBook.js contains two procedures:

  1. setupUserInterface takes care of retrieving the collection of all objects from the persistent data store and setting up an event handler (handleSaveButtonClickEvent) on the save button for handling click button events by saving the user input data;

  2. handleSaveButtonClickEvent reads the user input data from the form fields and then saves this data by calling the Book.add procedure.

pl.v.createBook = {
  setupUserInterface: function () {
    var saveButton = document.forms['Book'].commit;
    // load all book objects
    Book.retrieveAll();
    // set an event handler for the save/submit button
    saveButton.addEventListener("click", 
        pl.v.createBook.handleSaveButtonClickEvent);
    // handle the event when the browser window/tab is closed
    window.addEventListener("beforeunload", function () {
        Book.saveAll(); 
    });
  },
  handleSaveButtonClickEvent: function () {
    var formEl = document.forms['Book'];
    var slots = { isbn: formEl.isbn.value, 
        title: formEl.title.value, 
        year: formEl.year.value};
    Book.add( slots);
    formEl.reset();
  }
};