Add a cache module

This commit is contained in:
Tissevert 2018-12-29 14:15:23 +01:00
parent cb1a20546f
commit 75417035f6
4 changed files with 67 additions and 2 deletions

View file

@ -7,6 +7,7 @@
<script src="js/session.js"></script> <script src="js/session.js"></script>
<script src="js/async.js"></script> <script src="js/async.js"></script>
<script src="js/dom.js"></script> <script src="js/dom.js"></script>
<script src="js/cache.js"></script>
<script src="js/screen.js"></script> <script src="js/screen.js"></script>
<script src="js/buttons.js"></script> <script src="js/buttons.js"></script>
<script src="js/messaging.js"></script> <script src="js/messaging.js"></script>

View file

@ -1,4 +1,4 @@
function Automaton(async, dom, messaging, screen, session, ui) { function Automaton(async, cache, dom, messaging, screen, session, ui) {
var menus = { var menus = {
start: { start: {
entries: [ entries: [
@ -56,6 +56,15 @@ function Automaton(async, dom, messaging, screen, session, ui) {
name: 'textSpeed' name: 'textSpeed'
} }
}; };
var areas = new cache.make(function(key) {
messaging.send({tag: 'Load', area: key});
return async.bind(
messaging.receive(function(message) {
return message.tag == 'Area';
}),
function(message) { return async.wrap(message.contents); }
);
});
var game = session.get('game'); var game = session.get('game');
if(game != undefined) { if(game != undefined) {
menus.start.entries.unshift( menus.start.entries.unshift(

54
src/js/cache.js Normal file
View file

@ -0,0 +1,54 @@
function Cache(async) {
function Cache(loader) {
this.loader = loader;
this.loaded = {};
this.loading = {};
}
Cache.prototype.get = function(key) {
return function(f) {
if(this.loaded[key] != undefined) {
f(this.loaded[key]);
} else {
this.startLoading(key);
this.loading[key].push(f);
this.loader(key)(this.store(key));
}
}.bind(this);
};
Cache.prototype.warmUp = function(key) {
if(this.loaded[key] == undefined) {
this.startLoading(key);
this.loader(key)(this.store(key));
}
};
Cache.prototype.startLoading = function(key) {
if(this.loading[key] == undefined) {
this.loading[key] = [];
}
};
Cache.prototype.store = function(key) {
return function(value) {
this.loaded[key] = value;
for(var i = 0; i < this.loading[key].length; i++) {
this.loading[key][i](value);
}
this.loading[key] = null;
}.bind(this);
};
return {
make: make
};
function make(loader) {
var cache = new Cache(loader);
return {
get: cache.get.bind(cache),
warmUp: cache.warmUp.bind(cache)
};
}
}

View file

@ -4,7 +4,8 @@ window.addEventListener('load', function() {
dom = Dom(); dom = Dom();
screen = Screen(dom); screen = Screen(dom);
session = Session(async); session = Session(async);
cache = Cache(async);
buttons = Buttons(session); buttons = Buttons(session);
ui = UI(async, buttons, dom, screen, session); ui = UI(async, buttons, dom, screen, session);
automaton = Automaton(async, dom, messaging, screen, session, ui); automaton = Automaton(async, cache, dom, messaging, screen, session, ui);
}); });