moving to a constructor function
This commit is contained in:
parent
11f3cbfa7b
commit
8e27b25ddf
|
@ -1,46 +1,41 @@
|
||||||
var twitchCollector = {
|
function TwitchCollector(interval = 2e4) {
|
||||||
updateHooks: [],
|
const _hooks = {
|
||||||
data: null,
|
update: []
|
||||||
|
};
|
||||||
|
let _data = null;
|
||||||
|
|
||||||
|
async function _getData() {
|
||||||
|
const response = await fetch('/data');
|
||||||
|
const data = await response.json();
|
||||||
|
_update(data);
|
||||||
|
}
|
||||||
|
|
||||||
update: function(data) {
|
function _update(data) {
|
||||||
this.data = data;
|
_data = data;
|
||||||
var that = this;
|
|
||||||
this.updateHooks.forEach(function(v) {
|
|
||||||
v(that.data);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
registerHook: function(kind, callback) {
|
for (let hook of _hooks.update) {
|
||||||
switch (kind) {
|
hook(data);
|
||||||
case "update":
|
|
||||||
this.updateHooks.push(callback);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
start: function() {
|
|
||||||
this.getData();
|
|
||||||
var that = this;
|
|
||||||
window.setInterval(function() {
|
|
||||||
that.getData()
|
|
||||||
}, 20000);
|
|
||||||
},
|
|
||||||
|
|
||||||
getData: function() {
|
|
||||||
let xmlhttp = new XMLHttpRequest();
|
|
||||||
let url = "/data";
|
|
||||||
var that = this;
|
|
||||||
|
|
||||||
xmlhttp.onreadystatechange = function() {
|
|
||||||
if (this.readyState == 4 && this.status == 200) {
|
|
||||||
let data = JSON.parse(this.responseText);
|
|
||||||
if (data !== null) {
|
|
||||||
that.update(data);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
xmlhttp.open("GET", url, true);
|
|
||||||
xmlhttp.send();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function registerHooks(kind, callback) {
|
||||||
|
if (kind in _hooks) {
|
||||||
|
_hooks.kind.push(callback);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function data() {
|
||||||
|
return _data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function start() {
|
||||||
|
await _getData();
|
||||||
|
setInterval(_getData, interval);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
registerHooks,
|
||||||
|
start
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
Reference in New Issue
Block a user