-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathloader.js
69 lines (62 loc) · 1.69 KB
/
loader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
function Loader(assetsDir) {
this.assetsDir = assetsDir;
};
Loader.prototype = {
get status() {
return this._loaded + "/" + this._loading;
},
_loaded: 0,
_loading: 0,
assetsDir: "/",
images: {},
readyCallbacks: [],
ready: function(callback) {
this.readyCallbacks.push(callback);
this.runCallbacks();
},
loadImage: function(name) {
if(name == undefined)
game.error("Trying to load undefined image");
var image = this.images[name];
if (image) {
return image;
}
this._loading++;
image = new Image();
this.images[name] = image;
image.alt = name;
image.addEventListener("load", this.loaded.bind(this));
image.onerror = function(e) {
game.sendError("Cannot load " + name);
this.loaded();
}.bind(this);
image.src = this.assetsDir + name + "?v" + game.build;
return image;
},
loadImages: function(images) {
for (var name in images) {
images[name] = this.loadImage(images[name]);
images[name].name = name;
}
return images;
},
loaded: function() {
this._loaded++;
this.runCallbacks();
},
runCallbacks: function() {
while (this.readyCallbacks.length) {
if (this._loaded != this._loading)
return;
var callback = this.readyCallbacks.shift();
callback();
}
},
load: function(url, callback) {
this._loading++;
util.ajax(url, function(data) {
callback(JSON.parse(data));
this.loaded();
}.bind(this));
}
};