2

I have a Class names dialog. Inside this class I have a method hide() to hide the dialog box itself and its modal box. But I can't access hide function from "onclick" function. How can I access it?

class Dialog{
    constructor(id){
        this._dialogBox = $('.dialog#'+this.id);
        this._closeButton = this._dialogBox.find('span.closedialog');

        this._closeButton.on('click', function(){
            //how to access hide() function from here?
        });

    }
    hide(){
        this._dialogBack.hide();
        this.dialogBox.hide();
    }
}
1
  • 1
    Unrelated to the question I could not help to notice that it's probably a good idea for span.closedialog to be changed to button.closedialog (In HTML). This improves HTML semantics and brings significant benefits to usability and accessibility. Try to focus SPAN using only a keyboard TAB key... All this comes for free if using the proper semantics Commented Jul 20, 2020 at 14:00

3 Answers 3

2

Javascripts this context changes inside event listeners. You can work around this by adding the this context to a seperate variable:

class Dialog{
    constructor(id){
        this._dialogBox = $('.dialog#'+this.id);
        this._closeButton = this._dialogBox.find('span.closedialog');

        const self = this;

        this._closeButton.on('click', function(){
            //how to access hide() function from here?
            self.hide()
        });

    }
    hide(){
        this._dialogBack.hide();
        this.dialogBox.hide();
    }
}

As you can see I assign the this context to the variable self. After that you can access the class context with self.

Sign up to request clarification or add additional context in comments.

Comments

1

I think this should work for you

this._closeButton.on('click', this.hide.bind(this));

Context of this is different in event listener so you should bind your actual this to eventListener context

Comments

0

Change the onclick function's listener to arrow function if you are using es6+.. arrow functions don't override this

class Dialog{
    constructor(id){
        this._dialogBox = $('.dialog#'+this.id);
        this._closeButton = this._dialogBox.find('span.closedialog');

        this._closeButton.on('click', () => {
           this.hide();
        });

    }
    hide(){
        this._dialogBack.hide();
        this.dialogBox.hide();
    }
}````

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.