简体   繁体   中英

Attaching event handler on click pointing to function in class

Is it possible to attach an event handler on click pointing to function in class? Like this:

class SomeClass {
  render() {
    this.parentElement.append(`
      <form>
        <input type="text" onkeydown="${this.keydown()}"/>
        <button onclick="this.onclick();">Submit</button>
        <span></span>
      </form>
    `);
  }

  onkeydown() {}
  onclick() {}
}

Thank you.

The way you've done it here? No. Especially since append will only append nodes, not create nodes. Text is a node, but you won't see your form, just the HTML that would produce a form. However, even if you use innerHTML instead, it still won't work.

For the first function, you're not putting a reference to onkeypress , you're literally calling the function when you call render . If you remove the parenthesis you just wind calling the default value of the function. The same as if you put onkeypress.toString() . Not very helpful.

The second function, onclick is a bit trickier. It does call a function, just not the one you were hoping for. Understanding the this keyword in JavaScript is tricky. In this case, even though you're writing the html in a class, when the button is clicked the context of this is not that class. Instead it's the element that has the onclick listener attached, button . So what function does it call? Itself. Over and over again. This is a very good example of why it's not a good idea to name functions the same as native ones. Sadly though, even if you change it's name to something safer, like handleClick , it still doesn't work. The button (the current value of this ) just doesn't have the function you're trying to reference.

So, is it possible? Depends on what you're looking for. If you render the node and then add an event listener in the more traditional ways, sure. Just add this.parentElement.querySelector('button').onclick = this.handleClick; or this.parentElement.querySelector('input').addEventListener('keydown', this.handleKeyDown) after you add the form to the dom (using innerHTML or insertAdjacentHTML , instead of append ). Or follow Ibrahim's sugestion and create the elements using createElement and attaching the event handlers before you append them to the parent element. Though, if you want to have access to your classes this , you might want to bind them first.

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