鸿蒙应用开发之CustomeDialog弹窗中this指向问题

需求

收银台页面,选择银行卡支付时,首先弹短信验证弹窗,如下:
在这里插入图片描述
输入验证码且校验成功后,弹交易密码弹窗,如图:
在这里插入图片描述

代码逻辑

CashierPage.ets页面,点击后初始化弹窗,代码如下:

showSmsVerifyDialog(bankInfo: BankInfo) {
  this.smsVerifyDialogController = new CustomDialogController({
    builder: SMSVerifyDialog({
      bankInfo: bankInfo,
      onBindSuccess: this.onBindSuccess
    }),
    alignment: DialogAlignment.Center,
    autoCancel: false
  })
  this.smsVerifyDialogController.open()
}

SMSVerifyDialog.ets中,短信验证码验证如下:

async verifyVCode() {
  // 模拟网络请求成功后
  this.controller.close()
  this.onBindSuccess()
 }

其中onBindSuccessCashierPage.ets中定义,如下:

onBindSuccess() {
  this.showTradePwdDialog()
}

showTradePwdDialog() {
  this.tradePwdDialogController = new CustomDialogController({
    builder: TradePasswordDialog({
      onToSetPwdClick: this.onToSetPwdClick
    }),
    alignment: DialogAlignment.Center,
    autoCancel: false
  })
  this.tradePwdDialogController.open()
}

问题

短信验证码弹窗验证成功后,在执行onBindSuccess时,交易密码弹窗没有展示,报错如下:

page: pages/repay/CashierPage.js
Error message: is not callable
SourceCode:
this.showTradePwdDialog();
^
Stacktrace:
at onBindSuccess (/pages/repay/CashierPage.ets:42:5)
at verifyVCode (/ets/dialog/SMSVerifyDialog.ets:139:5)
at anonymous (/ets/dialog/SMSVerifyDialog.ets:100:15)

经定位,为this指向问题,在CashierPage.ets中的onBindSuccessthis.showTradePwdDialog();,该this实际指向为SMSVerifyDialog,而不是当前CashierPage中的this,因此会抛出异常。

解决方案

在创建SMSVerifyDialog的时候,为onBindSuccess绑定this即可,如下:

showSmsVerifyDialog(bankInfo: BankInfo) {
  this.smsVerifyDialogController = new CustomDialogController({
    builder: SMSVerifyDialog({
      bankInfo: bankInfo,
      onBindSuccess: this.onBindSuccess.bind(this)
    }),
    alignment: DialogAlignment.Center,
    autoCancel: false
  })
  this.smsVerifyDialogController.open()
}

再次运行尝试,解决,搞定~