2

I have been stuck for 4 days so it is going on SO!

Please reference the PreloadJS Definitions:

https://github.com/borisyankov/DefinitelyTyped/blob/master/preloadjs/preloadjs.d.ts

From line 26.

My question is, how do you addEventListener in typescript while also binding it to the class scope?

imagine (semi psudo):

class Test
{
     private _loader:createJS.AssetLoader;

     constructor()
     {
          this._loader = new createJS.AssetLoader();
          this._loader.addEventListener(???????????);
          this._loader.load();
     }

     onLoadComplete(???): ???
     {

     }
}
4

1 回答 1

3

使用 TypeScript 0.9.1.0:

class Test
{
     private _loader: createJS.AssetLoader;

     constructor()
     {
          this._loader = new createJS.AssetLoader();
          this._loader.addEventListenerthis.onLoadComplete);
          this._loader.load();
     }

     onLoadComplete = () =>
     {
        console.log(this.whatever);
     };
}

这里的重要部分是对函数使用成员初始化语法 ( member = value)onLoadComplete并为函数使用胖箭头 lambda 表达式 ( () => { ... })。这将正确捕获this回调中的上下文。

于 2013-08-09T19:50:21.207 回答