简体   繁体   中英

jQuery blur not triggering arrow functions inside a class

I'm new to JS classes and the fat arrow syntax. I read all I can but still can't figure out why are my functions not triggering. I know for sure the blur is happening on the inputs1-3, from console.logs I know the selector is ok, but still the console.log in validateForm() never gets triggered. What am I missing?

class FreezingScan {

constructor(parentElement) {
    this.parentElement = $(parentElement);
    console.log(this.parentElement);
    let subItems = $(parentElement).children(".scanSubItems");
    this.row1 = $(parentElement).children(".scanInput1");
    this.row2 = $(subItems).children(".scanInput2");
    this.row3 = $(subItems).children(".scanInput3");
    this.input1 = $(this.row1).children('input');
    this.input2 = $(this.row2).children('input');
    this.input3 = $(this.row3).children('input');
    this.clearBindEvents();
    this.bindEvents();
}

clearBindEvents() {
    this.input1.unbind();
    this.input2.unbind();
    this.input3.unbind();
}

bindEvents() {
    $(this.input1).blur(() => { this.validateForm() });
    $(this.input2).blur(() => { this.validateForm() });
    $(this.input3).blur(() => { this.validateForm() });
}

validateForm() { console.log('validated')  }

When you use the fat arrow syntax it changes the scope of the keyword this to be the parent scope and not of your function. You will either need to use the function key word instead or update to your to code to look at the target of the current event. Something like this:

bindEvents() {
    $(this.input1).blur((event) => { $(event.currentTarget).validateForm() });
    $(this.input2).blur((event) => { $(event.currentTarget).validateForm() });
    $(this.input3).blur((event) => { $(event.currentTarget).validateForm() });
}

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