简体   繁体   中英

How to set a load event for images on a complex Object in javascript

I'm loading a lot of images in javascript that are going to be needed in very different contexts. To easily access them in different contexts I created a tree-kind-of object. Something like this:

var imgs = {
  scene: new Image(),
  character1 :{
    left: {
       stand: new Image(),
       kick: new Image(),
       ...
    }
    right: {
       stand: new Image(),
       kick: new Image(),
       ...
    }
  character2 :{
    left: {
       stand: new Image(),
       kick: new Image(),
       ...
    }
    right: {
       stand: new Image(),
       kick: new Image(),
       ...
    }
}

Then I loaded the images:

imgs.scene.src = "scene.jpg";
imgs.character1.left.stand.src = "char1stand.png";
imgs.character1.left.kick.src = "char1kick.png";
...

Now I want to make a reliable method to attach an event to them. But the problem is the amount of levels I have. Is there a way of doing this without going into a complex system of for-in loops?

Since you want the handler being the same for all, you can set it up when you create the images.

var imagesLoaded = 0,
    total = 50; // set the total amount of images you have

function allLoaded() { /* do some stuff when all images are loaded */ };

function loaded() { // handler attached to all images
    // increase counter, if total is reached call allLoaded handler
    if (++imagesLoaded == total) allLoaded();
    /* do some more stuff */
}

function createImg() {
    var img = new Image();
    img.onload = loaded;
    return img;
}

Now replace in your imgs object all new Image() with createImg() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM