Почему другие мои функции и переменные класса становятся неопределенными после события jQuery click, запускающего одну из моих функций класса es6 - PullRequest
0 голосов
/ 24 января 2020

Я использую функцию класса es6 для редизайна моей страницы аутентификации. Когда пользователь щелкает ссылку «зарегистрироваться сейчас», предполагается, что функция showRegisterSection запускается так, что она переключается из раздела входа в систему в раздел регистрации страницы авторизации. Однако проблема заключается в том, что когда я пытаюсь получить доступ к локальным переменным, которые были инициализированы в функции конструктора и других функциях класса, для выполнения некоторых задач по перепроектированию, консоль браузера возвращает:

"functionName is не функция "

для функций и

" undefined "

значение для переменных.

Я пробовал разные функции и искал решения онлайн, но безрезультатно. Кроме того, если я скопирую код внутри функции и вставлю их в свой обработчик событий showRegisterSection или переназначу переменные внутри обработчика событий, все будет работать так, как задумано.

Имейте в виду, что первый функция, которая создает секцию входа в систему с именем ShowLoginSection, работает нормально и не вызывается из события. Это также функция, в которой настраивается событие щелчка, вызывающее showRegisterFunction.

Код представлен ниже:

    removeElement,
    insert_custom_social_login_before_target_Element
 } from './util';

export default class GulaitAuth{
    //if the isLogin variable is true, then we set up the login part else, we set up the register part
    constructor(isLoginSection, loginForm){
        this._isLoginSection = isLoginSection;
        this._loginForm = loginForm;
        this.initLocalVars();
    }

    /**
     * This function initializes local variables to their supposed values
     * except those passed in on creation of class obj.
     * This is due to an unknown issue where variables simply get reset  to undefined
     */
    initLocalVars(){
        this._loginDiv = document.querySelector('.woocommerce #customer_login').firstElementChild;
        this._registerDiv = document.querySelector('.woocommerce #customer_login').lastElementChild;
        this._myAccHeader = document.querySelector( '.woocommerce-account #main #contents header h2' );
        this._socialLoginContainer = document.querySelector( '#customer_login .apsl-login-networks.theme-2.clearfix' );
        this._authPageLoginForm = document.querySelector( '.woocommerce-page #customer_login form.login' );
    }

    setupAuthPage(){
        //setup the authentication page
        //css styles for Auth page if the loginForm exists on the page
        if( this._loginForm ){
            //remove header "MY ACCOUNT" from DOM
            removeElement(this._myAccHeader);

            //center the auth div
            jQuery('body.page-id-29 .container .row.sidebar-row').css('text-align', 'center');

            //style the Auth div - container
            jQuery('.woocommerce-account #contents').css({
                'max-width' : '38.5em',
                'display': 'inline-block',
                'text-align': 'initial',
                'padding': '1.5em',
                'border-top' : '.15em solid #DF1F26e5'
            });

            if( this._isLoginSection ){
                this.showLoginSection();
            } else {
                this.showRegisterSection();
            }

        }
    }

    /**
     * Show Login or Register Section based on _isLoginSection variable
     */
    showLoginOrRegister(){
        if(this._isLoginSection){
            //edit the login div
            jQuery(this._loginDiv).css( {'min-width' : '100%', 'padding' : '0', 'display' : 'block'} );

            //hide the register div
            jQuery(this._registerDiv).css( 'display', 'none' );
        } else {
            //hide the login div
            jQuery(this._loginDiv).css( 'display', 'none' );

            //edit the register div
            jQuery(this._registerDiv).css( {'min-width' : '100%', 'padding' : '0', 'display' : 'block'} );
        }

    }

    showLoginSection(){
        //show loginsection
        this.showLoginOrRegister();

        //remove full width on checkbox
        jQuery('.woocommerce #customer_login form.login input[type="checkbox"]').css('min-width', '0 !important');

        //remove extra spacing to the right
        jQuery('.woocommerce-account #main #contents .type-page').css('padding', '0');

        //row containing login and register forms is slightly pushed to the left with margin
        //this makes styling difficult as it has wierd positioning
        jQuery('div#customer_login.row').css('margin', '0');

        //remove extra space after the 'lost password?' section
        jQuery('.entry .entry-content .entry-summary').css('margin-bottom', '0');

        //remove login form margin
        jQuery('.woocommerce-page #customer_login form.login').css('margin', '0');

        //edit the login text
        jQuery('.woocommerce #customer_login h2')
        .css( { 
            'border-bottom' : '0',
            'margin-bottom' : '0',
            'padding-bottom' : '0.2em'
        } )
        .text('')
        .append(
            '<span id="login-text">Login</span><span id="or-text"> Or </span><span id="register-text">Register</span>'
        );

        jQuery('#or-text, #register-text').css( {
            'opacity' : '.2',
            'font-size' : '16px',
            'word-spacing' : '.12em',
            'font-weight' : '450'
        } );


        //Insert REGISTRATION Link after 'lost password' section
        jQuery("<p style='margin-top: 2em;'>Don't have an account? <strong id='register-link'><a href='#'>Register now</a></strong></p>")
        .insertAfter("#customer_login .login p.lost_password")
        .children("#register-link").click( this.showRegisterSection );

        //add an eventListener on the register link
        //jQuery('#register-link');

        //redesign the input form input fields
        jQuery('#customer_login .login .form-row.form-row-wide input').css( {
            'border' : '1px solid #ccc',
            'background' : 'white'
        } );

        //fb color = #1c74bc

        //Delete original social login and replace with custom version in the 
        //prefered position
        this.relocateSocialLogin();
    }

    showRegisterSection(){
        console.log('Register Link clicked');

        //set isLogin to false in order to show content as designed for the register form
        this._isLoginSection = false;

        //This function initializes local variables to their supposed values except
        //those passed in on creation of class obj. 
        //This is due to an unknown issue where variables simply get reset to undefined
        this.initLocalVars();

        //show register section
        //hide the login div
        jQuery(this._loginDiv).css( 'display', 'none' );

        //edit the register div
        jQuery(this._registerDiv).css( {'min-width' : '100%', 'padding' : '0', 'display' : 'block'} );
    }

    /**
     * Delete original social login and replace with custom version in the 
     * prefered position to fit design
     */
    relocateSocialLogin(){
        //Delete existing social login
        this._socialLoginContainer.parentNode.removeChild( this._socialLoginContainer );

        //Insert custom social login just before login form on auth page = my-account page
        insert_custom_social_login_before_target_Element( this._authPageLoginForm );

    }

}

1 Ответ

1 голос
/ 24 января 2020

Вы должны сохранить ссылку this в обработчике клика, определенном внутри showLoginSection()

Как написано: .children("#register-link").click( showRegisterSection );

Либо используйте функцию стрелки: .children("#register-link").click( e => this.showRegisterSection(e)); Тогда this ссылка на то, что this находится внутри showLoginSection(), будет сохранена. (наш подлинный экземпляр)

Альтернативами являются варианты .bind() Так что либо .children("#register-link").click( this.showRegisterSection.bind(this)); внутри showLoginSection()

, либо this.showRegisterSection = this.showRegisterSection.bind(this); внутри constructor(isLoginSection, loginForm){.

You Это необходимо сделать для всех функций, которые будут использоваться в качестве обработчиков событий, или в других ситуациях, когда функция не вызывается как метод класса GulaitAuth.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...