首页 > 解决方案 > TypeScript:将参数传递给回调函数

问题描述

以下代码来自azure-accountVSCode 扩展的代码示例的源代码。

export function activate(context: ExtensionContext) {
    const azureAccount = extensions.getExtension<AzureAccount>('ms-vscode.azure-account')!.exports;
    const subscriptions = context.subscriptions;
    subscriptions.push(commands.registerCommand('azure-account-sample.showSubscriptions', showSubscriptions(azureAccount)));
    subscriptions.push(commands.registerCommand('azure-account-sample.showAppServices', showAppServices(azureAccount)));
}

如您所见,代码定义了两个命令,这意味着当用户使用命令时azure-account-sample.showSubscription,它会调用函数showSubscriptions(azureAccount)

但是物体怎么会azureAccount这样通过???在我看来,代码应该这样写:

commands.registerCommand('azure-account-sample.showSubscriptions', showSubscriptions, azureAccount);

//commands.registerCommand
function registerCommand(callback, ...args){
    callback(args);
}

//defination of registerCommand from the source code of vscode api
export function registerCommand(command: string, callback: (...args: any[]) => any, thisArg?: any): Disposable;

标签: typescriptargumentsvscode-extensions

解决方案


showSubscriptions returns another function which is the actual callback

function showSubscriptions(account) {
    return function callback() {
        const sub = account.getSubscription()
    }
}

推荐阅读