Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to callback functions in TypeScript

this is my first question on SO so apologies if I mess this up somehow :)

I'm trying to play WebAudio using Typescript 0.9.1.1, but am currently stuck with the decodeAudioData function.

decodeAudioData takes several params: the audio data, a success callback and an error callback. 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.

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.

The compiled JS comes out as

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?

Thanks in advance :)

like image 332
Tom Evans Avatar asked Oct 03 '22 01:10

Tom Evans


1 Answers

Just take an argument in the lambda function. Here you go:

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

onDecode( buffer:AudioBuffer )
{
//  do things with buffer param
}
like image 139
basarat Avatar answered Oct 13 '22 09:10

basarat