ES6,PreloadJS和范围

时间:2016-12-30 13:15:18

标签: scope ecmascript-6 preloadjs

在PreloadJS的回调函数中,我正在失去范围。尝试了不同的方法,如箭头功能(在最高级别无效等等......任何提示?(抱歉格式错误的代码块(类防御等),仍然习惯这个编辑器,相信我,所有是工作代码)...

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 个答案:

答案 0 :(得分:0)

好的,仅在5分钟后更新....

将箭头函数添加为变量并将其传递给事件侦听器。这不是我喜欢的方式,但确实有效......

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
}

也许这可以帮助任何人。

仍然有兴趣看看是否有更好的方法......