TypeScript:将参数传递给回调函数
TypeScript: Passing parameters into a callback function
以下代码来自 azure-account
VSCode 扩展代码示例的源代码。
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;
showSubscriptions
returns 实际回调的另一个函数
function showSubscriptions(account) {
return function callback() {
const sub = account.getSubscription()
}
}
以下代码来自 azure-account
VSCode 扩展代码示例的源代码。
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;
showSubscriptions
returns 实际回调的另一个函数
function showSubscriptions(account) {
return function callback() {
const sub = account.getSubscription()
}
}