简体   繁体   中英

Call class function with addEventListener

I want to access the doSomething function when the button that the render function creates is clicked? I get the following error instead.

Uncaught ReferenceError: getMethod is not defined

main.js

    class Div {
    constructor(div){
        this.div = div;
    }

    init(){
        this.getMethod();
    }

    getMethod(){

        var div = this.div;
        var createButton = {
            render: function(){

                let button = `
                    <button
                    onclick="getMethod.doSomething(this)"
                    type="button">
                    Click Me!
                    </button>
                `;

                div.innerHTML = button;
            },

            doSomething: function(){
                // do something
            }

        }

        createButton.render();
    }
}


const div = new Div(document.querySelector('div'));
div.init();

There are multiple problems with your code.

  • Event handlers in html attributes (eg onclick ) get run in global scope, yet getMethod is defined in a local scope, the scope of your class.
  • getMethod does not have a property doSomething , I think you meant to write createButton.doSomething

To fix the first issue you have to define your button as an object, not just as text. Since text doesn't know anything about scope. Then you can addEventListener to add a handler for the click event. In the handler callback function's you will have access to all variables in your local scope (the scope of the getMethod function)

 class Div { constructor(div){ this.div = div; } init(){ this.getMethod(); } getMethod(){ var div = this.div; var createButton = { render: function(){ const button = document.createElement('button'); button.type = "button"; button.textContent = "Click Me!"; button.addEventListener('click', () => { createButton.doSomething(this) }) //clear inner html / delete all children div.innerHTML = ''; div.appendChild(button); }, doSomething: function(){ console.log("do something"); } } createButton.render(); } } const divElem = document.getElementById("mydiv"); const div = new Div(divElem); div.init();
 <div id="mydiv"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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