Adds unit test framework and a first unit test.
[quanweb.git] / js / src / 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,    // number of books available to be paged through
18     my.first = 0,    // first book to be displayed in current page (0-indexed)
19     my.ids = [],
20     my.last = (-1),  // last book to be displayed in the current page (0-indexed)
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(function(response) {return response.json();})
75             .then(function(jsonValue) {
76                 my.cache = jsonValue;
77                 notifyAll();    // inform all subscribers that the model has been updated
78             })
79             .catch(function(err) {
80                 var msg = 'Error fetching book details via URL:  ' + url + ': ' + err;
81                 console.log(msg, err.stack);
82                 report(msg);
83             });
84     };
85     
86     // ===============
87     // Private methods
88     
89     function notifyAll() {
90         for (var i in listeners) {
91             listeners[i].notify();
92         }
93     }
94     
95     return my;
96 })();