如何避免 Angular 中的多个 braintree.setup 实例?

How to avoid multiple instances of braintree.setup in Angular?

我有一个简单的 Braintree 模式付款表格 window:

$scope.displayModalBraintree = function () {
    $scope.modal = 'modal_payment_form.html', $scope.$on('$includeContentLoaded', function () {
        braintree.setup('tokenStringFromServer', 'paypal', {
            container: 'paypal',
            locale: 'da_dk',
            onReady: function (integration) {
                console.log('ready', integration)
            }
        })
    })
})

单击按钮执行 displayModalBraintree,第一次一切正常。然而,第二次单击按钮会生成两个 Paypal 按钮,并且日志显示准备就绪。

我已尝试按照 https://github.com/braintree/braintree-web/issues/29#issuecomment-137555915 中的说明使用拆解来销毁 braintree.setup 实例,但没有任何区别。

我在 Braintree 工作。

自该 Github 评论发布后,我们更新了有关拆解的文档。尝试在您的拆卸函数中设置 integration = null,如 code snippet here 中所示。如果这不起作用,我建议发布调用 teardown 的代码以帮助我们诊断您的问题。

完全披露:我在 Braintree 工作。如果您还有任何问题,请随时contact support.

您每次调用 $scope.displayModalBraintree 时都会为 $includeContentLoaded 设置一个新的侦听器。由于这些侦听器没有得到清理,因此您每次都创建一个新的。所以你第二次 运行 $scope.displayModalBraintree,它调用了两次 braintree.setup。第三次你 运行 它,因为现在有三个听众,它 运行 它三次。

一种解决方案是将侦听器设置在 $scope.displayModalBraintree 之外,如下所示:

var clientToken, braintreeVault;

$scope.$on('$includeContentLoaded', function () {
  braintree.setup(clientToken, 'paypal', {
    container: 'paypal',
    onReady: function (integration) {
        braintreeVault = integration;
    }
  })
});

$scope.displayModalBraintree = function () {
  $scope.getToken().then(function (token) {
    clientToken = token;
    $scope.modal = 'modal_payment_form?' + (new Date().getTime());
  })
};

另一种选择是在加载模式后销毁侦听器,但我认为将其从 $scope.displayModalBraintree 函数中提取出来更有意义。