I've something similar to the following code.
'use strict'
let Cache = {}
function Preloader(asset) {
let img = new Image();
img.onload = function() {
Cache[asset] = img;
window.dispatchEvent(new Event(`${asset}_preloaded`));
}
img.src = asset;
}
class Sprite {
constructor(params) {
this._src = params.src;
if(Cache[this._src]) {
this.init();
} else {
window.addEventListener(`${this._src}_preloaded`, () => this.init(), false);
Preloader(this._src);
}
}
init() {
window.removeEventListener(`${this._src}_preloaded`, () => this.init(), false);
this._width = Cache[this._src].width;
this._height = Cache[this._src].height;
}
}
When a new Sprite is created with an image as a parameter, it checks if the image is alredy cached. If it's not it calls the Preloader to load it. Events are used so the Preloader can tell the Sprite when the image has been loaded into the cache.
The event is added and dispatched correctly, also the init
function is called correctly, but the event isn't removed.