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">
  <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>

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:

  <h1>Create a new book record</h1>
  <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>
  <a href="index.html">Back to main menu</a>

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
    // set an event handler for the save/submit button
    // handle the event when the browser window/tab is closed
    window.addEventListener("beforeunload", function () {
  handleSaveButtonClickEvent: function () {
    var formEl = document.forms['Book'];
    var slots = { isbn: formEl.isbn.value, 
        title: formEl.title.value, 
        year: formEl.year.value};
    Book.add( slots);