Refactor JS into modules, and add basic MVC.
[quanweb.git] / js / BooksModel.js
1 // ==========
2 // BooksModel
3
4 var BooksModel = (function() {
5     
6     var my = {};
7     
8     // =================
9     // Private variables
10     
11     var listeners = [];
12     
13     // ================
14     // Public variables
15     
16     my.cache = [];
17     my.count = 0,
18     my.first = 0,
19     my.ids = [],
20     my.last = (-1),
21     my.map = {},    // map from book.Id to index into cache[]
22     my.pageSize = 20;
23
24     // ==============
25     // Public methods
26     
27     my.listen = function(subscriber) {
28         listeners.push(subscriber);
29     };
30     
31     my.refreshData = function () {
32         var i;
33         var url = '/info/?ids=';
34         my.map = {};
35         for (i = my.first; i <= my.last; ++i) {
36             if (i > my.first) {
37                 url += ',';
38             }
39             var id = my.ids[i];
40             url += id;
41             my.map[id] = i - my.first;
42         }
43
44         fetch(url, {method:'GET', cache:'default'})
45             .then(response => response.json())
46             .then((jsonValue) => {
47                 console.log('JSON response for info:  ', jsonValue);
48                 my.cache = jsonValue;
49                 notifyAll();    // inform all subscribers that the model has been updated
50             })
51             .catch(err => {
52                 var msg = 'Error fetching book details via URL:  ' + url + ': ' + err;
53                 console.log(msg, err.stack);
54                 report(msg);
55             });
56     };
57     
58     // ===============
59     // Private methods
60     
61     function notifyAll() {
62         for (var i in listeners) {
63             listeners[i].notify();
64         }
65     }
66     
67     return my;
68 })();