Refactor JS into modules, and add basic MVC.
[quanweb.git] / js / BooksModel.js
diff --git a/js/BooksModel.js b/js/BooksModel.js
new file mode 100644 (file)
index 0000000..0c0b915
--- /dev/null
@@ -0,0 +1,68 @@
+// ==========
+// BooksModel
+
+var BooksModel = (function() {
+    
+    var my = {};
+    
+    // =================
+    // Private variables
+    
+    var listeners = [];
+    
+    // ================
+    // Public variables
+    
+    my.cache = [];
+    my.count = 0,
+    my.first = 0,
+    my.ids = [],
+    my.last = (-1),
+    my.map = {},    // map from book.Id to index into cache[]
+    my.pageSize = 20;
+
+    // ==============
+    // Public methods
+    
+    my.listen = function(subscriber) {
+        listeners.push(subscriber);
+    };
+    
+    my.refreshData = function () {
+        var i;
+        var url = '/info/?ids=';
+        my.map = {};
+        for (i = my.first; i <= my.last; ++i) {
+            if (i > my.first) {
+                url += ',';
+            }
+            var id = my.ids[i];
+            url += id;
+            my.map[id] = i - my.first;
+        }
+
+        fetch(url, {method:'GET', cache:'default'})
+            .then(response => response.json())
+            .then((jsonValue) => {
+                console.log('JSON response for info:  ', jsonValue);
+                my.cache = jsonValue;
+                notifyAll();    // inform all subscribers that the model has been updated
+            })
+            .catch(err => {
+                var msg = 'Error fetching book details via URL:  ' + url + ': ' + err;
+                console.log(msg, err.stack);
+                report(msg);
+            });
+    };
+    
+    // ===============
+    // Private methods
+    
+    function notifyAll() {
+        for (var i in listeners) {
+            listeners[i].notify();
+        }
+    }
+    
+    return my;
+})();