Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Send An Argument To A Function Inside A Class Via An Event Listener In Vanilla JavaScript

This works as far as I can tell, but I'm new to this approach. Let me know if there are gotchas I should be watching out for

(check the console for the output)

The Problem, I Thought, But No, This Work

This is working without .call(). I thought this was where I was having the problem in other code. I'm going back to figure out where the problem was from.

JavaScript

class ProblemWidget {
  constructor() {}

  init() {
    problemWidgetInput.addEventListener("input", () => {
      this.level1(problemWidgetInput.value)
    })
  }

  level1(value) {
    console.log(`- Problem Widget Level 1:`)
    console.log(value)
    this.level2(value)
  }

  level2(value) {
    console.log(`- Problem Widget Level 2:`)
    console.log(value)
  }

}


document.addEventListener("DOMContentLoaded", () => {
  const pw = new ProblemWidget()
  pw.init()
})

This Also Works But Seems Unnecessary

This is using `.call()``, but that seems unnecessary, I'm leaving it here until I figured out what happened in the other

code that this seemed to fix.

JavaScript

class Widget {
  constructor() {}

  init() {
    workingWidgetInput.addEventListener("input", () => {
      this.level1.call(this, workingWidgetInput.value)
    })
  }

  level1(value) {
    console.log(`level1: ${value}`)
    this.level2(value)
  }

  level2(value) {
    console.log(`level2: ${value}`)
  }
}

document.addEventListener("DOMContentLoaded", () => {
  const w = new Widget()
  w.init()
})

References