如何点击一次后禁用Save按钮?避免重复提交导致信用卡重复
解决Save按钮多次点击导致重复创建信用卡的问题
核心问题分析
当前代码的关键错误是:异步操作(地址验证、身份校验、信用卡保存)还未完成时,就提前将isSaving设为false,导致按钮很快重新启用,用户可重复点击触发多次请求。
最佳修复方案
1. 修正状态管理逻辑
移除异步流程外的错误状态重置,确保所有异步操作完成(无论成功/失败)后再恢复按钮状态:
BillingInformation.prototype.addNewCard = function (parent, creditCard) { // 点击后立即禁用按钮 parent.isSaving(true); parent.isSettingDefault(true); creditCard.cardNumber(creditCard.cardNumber().replace(/-|\s/g, '')); let $form = $('#addNewCardForm' + creditCard.walletItemId()), cardNumber = creditCard.cardNumber(); parseDynamicFormElements($form); if ($form.valid()) { // 地址验证:添加失败回调处理状态 verifyAddress($form, function () { authentication.checkReAuthenticatedThenLaunchLoginOrExecuteTask(() => { creditCard .save() .then(response => { if (response.status === HTTP_STATUS_OK) { creditCard.walletItemId(response.content); parent.walletItems.push(creditCard); creditCard.lastFourDigits( creditCard.cardNumber() ? creditCard.cardNumber().substr(-4) : '' ); creditCard.obfuscatedCardNumber(cardNumber.replace(/.(?=.{4})/g, '*')); parent.newCardInstance(new CreditCard({paymentType: 'creditCards'})); checkForRedirect(); } else { let container = document.createElement('div'); container.append( 'We were unable to save your payment information. Please try again or give us a call at 1-800-461-8898' ); smartPak.ui.modal(container, { title: 'Unable to Save Payment Method', buttons: { Close: function (modal) { modal.close(); } } }); } }) // 处理保存请求的异常情况 .catch(error => { console.error('Save card failed:', error); }) // 无论成功/失败,最后统一重置状态 .finally(() => { parent.isSaving(false); parent.isSettingDefault(false); }); }); }, function() { // 地址验证失败时重置状态 parent.isSaving(false); parent.isSettingDefault(false); }); // 移除原代码中这里的parent.isSaving(false); } else { parent.isSaving(false); parent.isSettingDefault(false); } };
2. 增加二次校验(可选但推荐)
在方法开头添加校验,防止状态变更延迟导致的重复触发:
BillingInformation.prototype.addNewCard = function (parent, creditCard) { // 如果正在保存,直接返回,阻止重复执行 if (parent.isSaving()) return; parent.isSaving(true); parent.isSettingDefault(true); // 后续原有逻辑... };
现有绑定的有效性
你的Knockout绑定enable: !$root.isSaving()已经正确实现了按钮禁用逻辑,只要isSaving是Knockout的可观察对象(Observable),状态变更后按钮会自动更新禁用状态。
内容的提问来源于stack exchange,提问作者boogies
相关产品推荐
相关产品推荐

