The RemoteDataStore Module

In a moment, you will create a new module called RemoteDataStore. The job of RemoteDataStore will be to talk to a server on behalf of the rest of the application. It will have all the same methods as DataStoreadd, get, getAll, and remove – which it will use to communicate with the server (Figure 13.2).

Figure 13.2  DataStore vs RemoteDataStore

DataStore vs RemoteDataStore

You will be able to use an instance of RemoteDataStore in place of DataStore without having to change your Truck, FormHandler, or CheckList modules. (You will not be deleting your DataStore module, though. You might want to create a future enhancement allowing CoffeeRun to switch between the two storage modules based on whether the app is running online or offline.)

RemoteDataStore’s methods will communicate asynchronously with the server by sending a network request in the background. When the browser receives the response from the server, it has an opportunity to invoke a callback.

Each of RemoteDataStore’s methods will accept a function argument that will be invoked after the response arrives with any data from the server.

Create a new scripts/remotedatastore.js file and add a <script> tag for it in index.html.

...
    <script src="scripts/validation.js" charset="utf-8"></script>
    <script src="scripts/checklist.js" charset="utf-8"></script>
    <script src="scripts/formhandler.js" charset="utf-8"></script>
    <script src="scripts/remotedatastore.js" charset="utf-8"></script>
    <script src="scripts/datastore.js" charset="utf-8"></script>
    <script src="scripts/truck.js" charset="utf-8"></script>
    <script src="scripts/main.js" charset="utf-8"></script>
  </body>
</html>

Save index.html. In remotedatastore.js, import the App namespace and jQuery, then create an IIFE module with a constructor named RemoteDataStore. The constructor should accept an argument for a remote server URL and throw an error if a URL is not passed in. At the end of the module definition, export the RemoteDataStore to the App namespace:

(function (window) {
  'use strict';
  var App = window.App || {};
  var $ = window.jQuery;

  function RemoteDataStore(url) {
    if (!url) {
      throw new Error('No remote URL supplied.');
    }

    this.serverUrl = url;
  }

  App.RemoteDataStore = RemoteDataStore;
  window.App = App;

})(window);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.244.250