Turbo.js当你点击一个link是发生了什么


快速的总结:
  1. 阻止浏览器打开link
  2. 通过历史Api修改browser URL
  3. 通过fetch请求新页面
  4. Render渲染响应的HTML通过替换当前body元素,合并<head>元素内容。



window.Turbo = Turbo
Turbo.start()

The start method in turn starts the session by calling session.start() method.
// src/core/session.js

export class Session {
    
  linkClickObserver = new LinkClickObserver(this, window)
  formSubmitObserver = new FormSubmitObserver(this, document)

  start() {
    if (!this.started) {
      // ...
      this.linkClickObserver.start()
      this.formSubmitObserver.start()
      // ...
      this.history.start()
      this.started = true
      this.enabled = true
    }
  }
}


// src/core/session.js

export class Session {
    
  linkClickObserver = new LinkClickObserver(this, window)
  formSubmitObserver = new FormSubmitObserver(this, document)

  start() {
    if (!this.started) {
      // ...
      this.linkClickObserver.start()
      this.formSubmitObserver.start()
      // ...
      this.history.start()
      this.started = true
      this.enabled = true
    }
  }
}


export class LinkClickObserver {
  started = false

  constructor(delegate, eventTarget) {
    this.delegate = delegate        // set to 'session'
    this.eventTarget = eventTarget  // set to 'window'
  }

  start() {
    if (!this.started) {
      this.eventTarget.addEventListener("click", this.clickCaptured, true)
      this.started = true
    }
  }
}


When LinkClickObserver starts, it adds an event listener for the click event on the window .
However, instead of attaching a handler on event bubbling phase, it uses event capturing by setting the third optional, boolean parameter useCapture to true.

https://www.akshaykhot.com/turbo-internals/
https://www.akshaykhot.com/introduction-to-hotwire/

阅读量: 859
发布于:
修改于: