-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
126 lines (107 loc) · 2.4 KB
/
index.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
'use strict';
/**
* Representation of one single file that will be loaded.
*
* @constructor
* @param {String} url The file URL.
* @param {Function} fn Optional callback.
* @api private
*/
function Floppy(url, fn) {
if (!(this instanceof Floppy)) return new Floppy(url, fn);
this.readyState = Floppy.LOADING;
this.start = +new Date();
this.callbacks = [];
this.dependent = 0;
this.cleanup = [];
this.url = url;
if ('function' === typeof fn) {
this.add(fn);
}
}
//
// The different readyStates for our Floppy class.
//
Floppy.DEAD = -1;
Floppy.LOADING = 0;
Floppy.LOADED = 1;
/**
* Added cleanup hook.
*
* @param {Function} fn Clean up callback
* @returns {Floppy}
* @api public
*/
Floppy.prototype.unload = function unload(fn) {
this.cleanup.push(fn);
return this;
};
/**
* Add a new dependent.
*
* @param {Function} fn Completion callback.
* @returns {Boolean} Callback successfully added or queued.
* @api private
*/
Floppy.prototype.add = function add(fn) {
if (Floppy.LOADING === this.readyState) {
this.callbacks.push(fn);
} else if (Floppy.LOADED === this.readyState) {
fn();
} else {
fn(new Error('Floppy has been destroyed.'));
return false;
}
this.dependent++;
return true;
};
/**
* Remove a dependent. If all dependent's are ejected we will automatically
* destroy the loaded file from the environment.
*
* @returns {Boolean}
* @api public
*/
Floppy.prototype.eject = function eject() {
if (0 === --this.dependent) {
this.destroy();
return true;
}
return false;
};
/**
* Execute the callbacks.
*
* @param {Error} err Optional error.
* @returns {Floppy}
* @api public
*/
Floppy.prototype.exec = function exec(err) {
this.readyState = Floppy.LOADED;
if (!this.callbacks.length) return this;
for (var i = 0; i < this.callbacks.length; i++) {
this.callbacks[i].apply(this.callbacks[i], arguments);
}
this.callbacks.length = 0;
if (err) this.destroy();
return this;
};
/**
* Destroy the file.
*
* @returns {Floppy}
* @api public
*/
Floppy.prototype.destroy = function destroy() {
this.exec(new Error('Resource has been destroyed before it was loaded'));
if (this.cleanup.length) for (var i = 0; i < this.cleanup.length; i++) {
this.cleanup[i]();
}
this.readyState = Floppy.DEAD;
this.cleanup.length = this.dependent = 0;
return this;
};
//
// Expose the instance.
//
module.exports = Floppy;