ES6, PreloadJS and scope

247 views Asked by At

In PreloadJS' callback functions I'm losing scope. Have tried different methods such as an arrow function (which aren't valid on the highest level etc... Any tips? (sorry for the malformed code block (class defenition etc), still getting used to this editor, trust me, all is working code)...

import Navigation from './Navigation'
import ajax from "./Ajax";
import Helper from "./Helper";

let preload = null;

export default class Page{  

    constructor(){
        this.preload = new createjs.LoadQueue();
        this.preload.addEventListener("fileprogress", this.handleFileProgress);
        this.preload.addEventListener("fileload", this.handleFileComplete);

    }



    initPage(_arg = []){        
        this.buildPage(this.thePage);
    }


    buildPage(_content){
        this.loadImage(item.featured_image_thumbnail_url);

    }

    handleFileComplete(event){      

        console.log(event);
        console.log(this); // undefined

        let el = document.getElementById('heroImage');
        let loader = el.getElementsByClassName('loader')[0];
        this.showPage(); // cannot read property showPage of undefined

    }

    // small arrow test, doesn't seem valid
    //handleFileComplete = (event) =>{
    //    this.showPage();
    //}

    handleFileProgress(event){      
        let hero = document.getElementById('heroImage')
        let loader = hero.getElementsByClassName('loader')[0];
    }

    loadImage(_img){      

        let el = document.getElementById('heroImage');
        let loader = el.getElementsByClassName('loader')[0];

        let loadManifest = [
          {
            id:   'pat',
            src:  _img,
            scope: this
          }];     

        this.preload.loadManifest(loadManifest, true);  
    }

    showPage(){
        //Helper.removeClass(document.getElementById('mytest','hidden'));
    }       

}
1

There are 1 answers

0
Patrick Teulings On

Ok, update after only 5 min....

Addded an arrow function as a variable and passed that on to the event listener. This is not my preferred way but it does work though...

constructor(){

    let handleFileCompleted = (event) => {
        this.showPage(event)
    }       

    this.preload = new createjs.LoadQueue();
    this.preload.addEventListener("fileprogress", this.handleFileProgress);
    this.preload.addEventListener("fileload", handleFileCompleted);
}

showPage(event){
   console.log('I'm now reachable!');
   console.log(event); // fileload event
}

Perhaps this can help anybody out.

Still interested to see if there's a better way though...