Rails Turbo Stimulus 中遇到 问题

ecloud · April 04, 2022 · Last by ecloud replied at April 04, 2022 · 319 hits

JS 代码如下:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {

  static targets = [ "progress", "volume", "progressbar"]

  connect() {
    if(!window.__audioEl) {
      window.__audioEl = document.createElement("audio")
      window.__audioEl.addEventListener("timeupdate", this.onTimeUpdate, true)
    }   
  }

  onTimeUpdate() {
    // undefined
    console.log(this.progressTarget)
  }
}

onTimeUpdate 函数中无法访问 this.progressTarget。刚学 Stimulus,感觉有点困惑。

这是原生 JavaScript 的问题

window.__audioEl.addEventListener("timeupdate", this.onTimeUpdate, true)

这里 onTimeUpdate 的上下文是 windowsthis 指向的是 window

要改成:

window.__audioEl.addEventListener("timeupdate", this.onTimeUpdate.bind(this), true)

顺便提一下你将来会遇到的问题,怎么解绑:


connect() {
  // ...
  this.onTimeUpdateHandler = this.onTimeUpdate.bind(this)
  window.__audioEl.addEventListener("timeupdate", this.onTimeUpdateHandler, true)
}

disconnect() {
  window.__audioEl.removeEventListener("timeupdate", this.onTimeUpdateHandler, true)
}
Reply to Rei

非常感谢,完美解决问题。

You need to Sign in before reply, if you don't have an account, please Sign up first.