Search code examples
javascripteventspreventdefault

How to preventDefault inside method


When executing submit, "e" is undefined... How to preventDefault and then execute()? I've tried "this.execute" (without brackets), but then the variable "form" is not accessible. Also tried this:

this.form.addEventListener("submit", function(e){e.preventDefault(); this.execute();}, false);

but not working.

class Filters {
    form;

    constructor(form) {
        this.form = form;
        this.form.addEventListener("submit", this.execute(), false);
    }

    execute(e) {
        e.preventDefault();
        [...]
    }
}

let f = new Filters([...],[...]);

Solution

  • You need to pass the event to your execute method as a parameter like shown below.

    class Filters {
        form;
    
        constructor(form) {
            this.form = form;
            // Either use an arrow function or this.execute.bind(this) 
            this.form.addEventListener("submit", e => this.execute(e), false);
        }
    
        execute(e) {
            e.preventDefault();
            [...]
        }
    }