在TypeScript中向回调函数传递参数

5
这是我在SO上的第一个问题,如果有什么问题请见谅:)
我正在尝试使用Typescript 0.9.1.1播放WebAudio,但目前卡在了decodeAudioData函数。
decodeAudioData需要几个参数:音频数据、成功回调和错误回调。成功回调传递了一个“buffer”参数,我需要访问它,我想使用lambda函数来实现,但我不知道该怎么做。
我的(无法工作的)代码如下:
init()
{
    audio_context.decodeAudioData( array_buffer, () => this.onDecode( buffer ) ) ;
}

onDecode( buffer:AudioBuffer )
{
//  do things with buffer param
}

我可以编写一个长格式的函数,像这样:

audio_context.decodeAudioData( array_buffer, function( buffer) { /* do stuff */ } ) ;

但是如果我能使用lambda函数,长期来看,代码会更加简洁易读。

编译后的JS代码为:

audio_context.decodeAudioData(array_buffer, function () {
        return _this.onDecode(buffer);
    }, function () {
        return _this.onError();
    });

我可以通过将“缓冲区”参数插入到函数声明中手动使其工作,但是我该如何编写代码,以便TypeScript知道我的意图呢?

提前致谢 :)

1个回答

4

只需在lambda函数中传入一个参数即可。这里是代码示例:

init()
{
    audio_context.decodeAudioData( array_buffer, (buffer) => this.onDecode( buffer ) ) ;
}

onDecode( buffer:AudioBuffer )
{
//  do things with buffer param
}

1
当我单独编写函数时,像上面那样,在我的异步成功回调函数中'this'为null。有什么想法吗? - sudhir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接