简体   繁体   English

将参数传递给TypeScript中的回调函数

[英]Passing parameters to callback functions in TypeScript

this is my first question on SO so apologies if I mess this up somehow :) 这是我关于SO的第一个问题,如果我以某种方式弄乱了,请您道歉:)

I'm trying to play WebAudio using Typescript 0.9.1.1, but am currently stuck with the decodeAudioData function. 我正在尝试使用Typescript 0.9.1.1播放WebAudio,但是当前卡在了decodeAudioData功能上。

decodeAudioData takes several params: the audio data, a success callback and an error callback. defineAudioData具有几个参数:音频数据,成功回调和错误回调。 The success callback passes a "buffer" param that I need to access, and I'd like to do this using a lambda function, but I don't know how to do it. 成功回调传递一个我需要访问的“缓冲区”参数,我想使用lambda函数来执行此操作,但是我不知道该怎么做。

My (non-working) code is: 我的(无效)代码是:

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

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

I could wite a long-form function like this: 我可以等一个长形式的函数:

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

but it's cleaner and easier long-term if I can use lambda functions. 但是如果我可以使用lambda函数,从长远来看它会更清洁,更轻松。

The compiled JS comes out as 编译后的JS显示为

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

so I can make it work manually by jamming in a "buffer" param into the function declaration - but how do I write it so TypeScript knows what I'm trying to do? 因此,我可以通过将“缓冲区”参数塞入函数声明中来使其手动工作-但是如何编写它,以便TypeScript知道我要做什么?

Thanks in advance :) 提前致谢 :)

Just take an argument in the lambda function. 只需在lambda函数中接受一个参数即可。 Here you go: 干得好:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM