Adds unit test framework and a first unit test.
[quanweb.git] / js / src / BooksModel.js
diff --git a/js/src/BooksModel.js b/js/src/BooksModel.js
new file mode 100644 (file)
index 0000000..1626d29
--- /dev/null
@@ -0,0 +1,96 @@
+// ==========
+// BooksModel
+
+var BooksModel = (function() {
+    
+    var my = {};
+    
+    // =================
+    // Private variables
+    
+    var listeners = [];
+    
+    // ================
+    // Public variables
+    
+    my.cache = [];
+    my.count = 0,    // number of books available to be paged through
+    my.first = 0,    // first book to be displayed in current page (0-indexed)
+    my.ids = [],
+    my.last = (-1),  // last book to be displayed in the current page (0-indexed)
+    my.map = {},     // map from book.Id to index into cache[]
+    my.pageSize = 20;
+
+    // ==============
+    // Public methods
+    
+    my.adjustPos = function(setting) {
+
+        var value = parseInt(setting);
+
+        var prev = {
+            first: my.first,
+            last: my.last,
+        };
+        
+        var maxFirst = Math.max(0, my.count - my.pageSize);
+        
+        if (value < 0) {
+            my.first = 0;
+        } else if (value > maxFirst) {
+            my.first = maxFirst;
+        } else {
+            my.first = value;
+        }
+    
+        my.last = my.first + my.pageSize - 1;
+        if (my.last >= my.count) {
+            my.last = my.count - 1;
+        }
+        
+        if (prev.first !== my.first || prev.last !== my.last) {
+            my.refreshData();
+        }
+    };
+    
+    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(function(response) {return response.json();})
+            .then(function(jsonValue) {
+                my.cache = jsonValue;
+                notifyAll();    // inform all subscribers that the model has been updated
+            })
+            .catch(function(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;
+})();