0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Hidden
  • 3,895
  • 3
  • 11
  • 11
  • I have a question here. Why are you create distinct events for all the images? You could have a single event that stays on window or Document for that matter and have it trigger whenever any image loads and pass the image src as data to the event – Akshay Khandelwal Jun 19 '16 at 14:32
  • @AndrewL there are no type annotations, so this looks like normal JS using ES6 classes and block scope. – ssube Jun 19 '16 at 14:32
  • @AndrewL this is es6. – Daniel A. White Jun 19 '16 at 14:32
  • you are passing 2 separate functions - just pass `this.init`. – Daniel A. White Jun 19 '16 at 14:32
  • @DanielA.White: That's the problem, yeah, but passing `this.init` would lose `this` during the call; `init` isn't an arrow function or a bound function. – T.J. Crowder Jun 19 '16 at 14:33
  • @DanielA.White I'm not passing two functions. I'm passing one function which then calls another function. I'm using an arrow function there to preserve `this` – Hidden Jun 19 '16 at 14:40
  • Based on @T.J.Crowder comment I've solved the problem by moving the `init` fuction into the constructor as an arrow function. Thank you! – Hidden Jun 19 '16 at 15:07
  • @Hidden: Glad that helped. What Daniel meant was you're passing two separate functions to `addEventListener` and `removeEventListener` (that is, one each, but not the *same* one, which is why it won't work -- has to be the same function). – T.J. Crowder Jun 19 '16 at 15:24

0 Answers0