1

I have a handy function that can load an array of images, and execute a callback when all the images have been loaded.

For most of my time with JavaScript, I've been coding in the functional paradigm, and would like to translate to object-oriented.

I can't seem to properly reference the this of unit.loadedImage. Any help with referencing this within the preloadImage() sub-method would be deeply appreciated.

class Unit {
    constructor() {
        this.loadedImages = [];
    }

    preloadImages(urls, allImagesLoadedCallback) {
        let loadedCounter = 0;
        let toBeLoadedNumber = urls.length;
        urls.forEach(function(url) {
            preloadImage(url, function() {
                loadedCounter++;
                console.log(`Number of loaded images: ${loadedCounter}`);
                if (loadedCounter == toBeLoadedNumber) {
                    allImagesLoadedCallback();
                }
            });
        });

        function preloadImage(url, anImageLoadedCallback) {
            let img = new Image();
            img.src = url;
            img.onload = anImageLoadedCallback;
            this.loadedImages.push(img); // error is here, "Cannot read property 'loadedImages' of undefined"
        }
    }
}

let unit = new Unit();
console.log(unit);

unit.preloadImages([
    'img/image-halo.png',
    'img/image-clouds.png',
    'img/image-glasses.png',
    'img/image-fire.png',
    './img/image-particle.png'
], function() {
    console.log('All images loaded.');
});
Sam Sverko
  • 1,480
  • 4
  • 15
  • 32

0 Answers0