Refactor search into its own controller.
[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.adjustPos = function(setting) {
28
29         var value = parseInt(setting);
30
31         var prev = {
32             first: my.first,
33             last: my.last,
34         };
35         
36         var maxFirst = Math.max(0, my.count - my.pageSize);
37         
38         if (value < 0) {
39             my.first = 0;
40         } else if (value > maxFirst) {
41             my.first = maxFirst;
42         } else {
43             my.first = value;
44         }
45     
46         my.last = my.first + my.pageSize - 1;
47         if (my.last >= my.count) {
48             my.last = my.count - 1;
49         }
50         
51         if (prev.first !== my.first || prev.last !== my.last) {
52             my.refreshData();
53         }
54     };
55     
56     my.listen = function(subscriber) {
57         listeners.push(subscriber);
58     };
59     
60     my.refreshData = function () {
61         var i;
62         var url = '/info/?ids=';
63         my.map = {};
64         for (i = my.first; i <= my.last; ++i) {
65             if (i > my.first) {
66                 url += ',';
67             }
68             var id = my.ids[i];
69             url += id;
70             my.map[id] = i - my.first;
71         }
72
73         fetch(url, {method:'GET', cache:'default'})
74             .then(response => response.json())
75             .then((jsonValue) => {
76                 console.log('JSON response for info:  ', jsonValue);
77                 my.cache = jsonValue;
78                 notifyAll();    // inform all subscribers that the model has been updated
79             })
80             .catch(err => {
81                 var msg = 'Error fetching book details via URL:  ' + url + ': ' + err;
82                 console.log(msg, err.stack);
83                 report(msg);
84             });
85     };
86     
87     // ===============
88     // Private methods
89     
90     function notifyAll() {
91         for (var i in listeners) {
92             listeners[i].notify();
93         }
94     }
95     
96     return my;
97 })();