繁体   English   中英

JavaScript类:动态默认值

[英]JavaScript Class: Dynamic Default Value

尝试在下面的Magento 2 JavaScript类(cc-form.js)中将creditCardExpMonth设置为当前月份。 选项月份值为1到12。 当我手动将月份值(如3 creditCardExpMonth:3)添加到默认值:{}时,它可以正常工作。 我似乎无法弄清楚如何将其动态设置为当月。 我接受允许用户选择覆盖该值的任何解决方案,但我更希望它位于此类内或html页面上,而不是页面加载后的JQuery更新。

我在此类中创建了getCurrentMonth()函数,但无法弄清楚如何正确访问它以将creditCardExpMonth设置为默认值。

define(
[
    'underscore',
    'Mageplaza_Osc/js/view/payment/default',
    'Magento_Payment/js/model/credit-card-validation/credit-card-data',
    'Magento_Payment/js/model/credit-card-validation/credit-card-number-validator',
    'mage/translate'
],
function (_, Component, creditCardData, cardNumberValidator, $t) {
    return Component.extend({
        defaults: {
            creditCardType: '',
            creditCardExpYear: '',
            creditCardExpMonth: '',
            creditCardNumber: '',
            creditCardSsStartMonth: '',
            creditCardSsStartYear: '',
            creditCardVerificationNumber: '',
            selectedCardType: null
        },

        initObservable: function () {
            this._super()
                .observe([
                    'creditCardType',
                    'creditCardExpYear',
                    'creditCardExpMonth',
                    'creditCardNumber',
                    'creditCardVerificationNumber',
                    'creditCardSsStartMonth',
                    'creditCardSsStartYear',
                    'selectedCardType'
                ]);
            return this;
        },

        initialize: function() {
            var self = this;
            this._super();


            //Set credit card number to credit card data object
            this.creditCardNumber.subscribe(function(value) {
                var result;
                self.selectedCardType(null);

                if (value == '' || value == null) {
                    return false;
                }
                result = cardNumberValidator(value);

                if (!result.isPotentiallyValid && !result.isValid) {
                    return false;
                }
                if (result.card !== null) {
                    self.selectedCardType(result.card.type);
                    creditCardData.creditCard = result.card;
                }

                if (result.isValid) {
                    creditCardData.creditCardNumber = value;
                    self.creditCardType(result.card.type);
                }
            });

            //Set expiration year to credit card data object
            this.creditCardExpYear.subscribe(function(value) {
                creditCardData.expirationYear = value;
            });

            //Set expiration month to credit card data object
            this.creditCardExpMonth.subscribe(function(value) {
                creditCardData.expirationYear = value;
            });

            //Set cvv code to credit card data object
            this.creditCardVerificationNumber.subscribe(function(value) {
                creditCardData.cvvCode = value;
            });
        },

        getCode: function() {
            return 'cc';
        },
        getData: function() {
            return {
                'method': this.item.method,
                'additional_data': {
                    'cc_cid': this.creditCardVerificationNumber(),
                    'cc_ss_start_month': this.creditCardSsStartMonth(),
                    'cc_ss_start_year': this.creditCardSsStartYear(),
                    'cc_type': this.creditCardType(),
                    'cc_exp_year': this.creditCardExpYear(),
                    'cc_exp_month': this.creditCardExpMonth(),
                    'cc_number': this.creditCardNumber()
                }
            };
        },
        getCcAvailableTypes: function() {
            return window.checkoutConfig.payment.ccform.availableTypes[this.getCode()];
        },
        getIcons: function (type) {
            return window.checkoutConfig.payment.ccform.icons.hasOwnProperty(type)
                ? window.checkoutConfig.payment.ccform.icons[type]
                : false
        },
        getCcMonths: function() {
            return window.checkoutConfig.payment.ccform.months[this.getCode()];
        },
        getCcYears: function() {
            return window.checkoutConfig.payment.ccform.years[this.getCode()];
        },
        hasVerification: function() {
            return window.checkoutConfig.payment.ccform.hasVerification[this.getCode()];
        },
        hasSsCardType: function() {
            return window.checkoutConfig.payment.ccform.hasSsCardType[this.getCode()];
        },
        getCvvImageUrl: function() {
            return window.checkoutConfig.payment.ccform.cvvImageUrl[this.getCode()];
        },
        getCvvImageHtml: function() {
            return '<img src="' + this.getCvvImageUrl()
                + '" alt="' + $t('Card Verification Number Visual Reference')
                + '" title="' + $t('Card Verification Number Visual Reference')
                + '" />';
        },
        getSsStartYears: function() {
            return window.checkoutConfig.payment.ccform.ssStartYears[this.getCode()];
        },
        getCcAvailableTypesValues: function() {
            return _.map(this.getCcAvailableTypes(), function(value, key) {
                return {
                    'value': key,
                    'type': value
                }
            });
        },
        getCcMonthsValues: function() {
            return _.map(this.getCcMonths(), function(value, key) {
                return {
                    'value': key,
                    'month': value.substring(0,2)
                }
            });
        },  
        getCcYearsValues: function() {
            return _.map(this.getCcYears(), function(value, key) {
                return {
                    'value': key,
                    'year': value
                }
            });
        },
        getCurrentMonth: function() {
            var d = new Date(); 
            var n = d.getMonth() + 1; 
            return n;
        },
        getCurrentYear: function() {
            var d = new Date(); 
            var n = d.getYear(); 
            return n;
        },
        getSsStartYearsValues: function() {
            return _.map(this.getSsStartYears(), function(value, key) {
                return {
                    'value': key,
                    'year': value
                }
            });
        },
        isShowLegend: function() {
            return false;
        },
        getCcTypeTitleByCode: function(code) {
            var title = '';
            _.each(this.getCcAvailableTypesValues(), function (value) {
                if (value['value'] == code) {
                    title = value['type'];
                }
            });
            return title;
        },
        formatDisplayCcNumber: function(number) {
            return 'xxxx-' + number.substr(-4);
        },
        getInfo: function() {
            return [
                {'name': 'Credit Card Type', value: this.getCcTypeTitleByCode(this.creditCardType())},
                {'name': 'Credit Card Number', value: this.formatDisplayCcNumber(this.creditCardNumber())}
            ];
        }
    });
});

这是带有选择数据绑定的剔除HTML,以防万一需要(摘自Magento付款cc-form.html):

<select  name="payment[cc_exp_month]"
                             class="select select-month"
                             data-bind="attr: {id: getCode() + '_expiration', 'data-container': getCode() + '-cc-month', 'data-validate': JSON.stringify({required:true, 'validate-cc-exp':'#' + getCode() + '_expiration_yr'})},
                                        enable: isActive($parents),
                                        options: getCcMonthsValues(),  
                                        optionsValue: 'value',
                                        optionsText: 'month',
                                        optionsCaption: $t('Month'),
                                        value: creditCardExpMonth">
                    </select>

如果每次页面加载时都运行此脚本,则可以执行以下操作:

defaults: {
            creditCardType: '',
            creditCardExpYear: '',
            creditCardExpMonth: (function(){
                                  return ((new Date()).getMonth()+1);
                                 })(),
            creditCardNumber: '',
            creditCardSsStartMonth: '',
            creditCardSsStartYear: '',
            creditCardVerificationNumber: '',
            selectedCardType: null
        }

或者,如果您想要更干净的东西,可以将代码重构为在创建此对象之前定义的函数:

function (_, Component, creditCardData, cardNumberValidator, $t) {
    function getCurrentMonth() {
        return ((new Date()).getMonth()+1);
    }
    return Component.extend({
        defaults: {
            creditCardType: '',
            creditCardExpYear: '',
            creditCardExpMonth: getCurrentMonth(),
            creditCardNumber: '',
            creditCardSsStartMonth: '',
            creditCardSsStartYear: '',
            creditCardVerificationNumber: '',
            selectedCardType: null
        },

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM