hotwired / stimulus

A modest JavaScript framework for the HTML you already have
https://stimulus.hotwired.dev/
MIT License
12.55k stars 420 forks source link

Error when trying to access target element after trix-editor input #172

Closed rolandasb closed 5 years ago

rolandasb commented 5 years ago

👋

When I try to access target element which is after <trix-editor></trix-editor>, browser throws an Error: Missing target element error. This happens only on Chrome (Version 68.0.3440.84) - on Safari and Firefox DE it works fine.

<div class="form" data-controller="post-form">
  <div class="form-group">
    <input type="text" placeholder="title" data-target="post-form.titleInput">
  </div>

  <div class="form-group">
    <input id="x" type="hidden" name="content">
    <trix-editor input="x" placeholder="content"></trix-editor>
  </div>

  <input type="text" placeholder="author" data-target="post-form.authorInput">
</div>
import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "titleInput", "authorInput" ]

  connect() {
    console.log(this.titleInputTarget);
    console.log(this.authorInputTarget);
  }
}

I threw Rails project for quick reproduction: https://github.com/rolandasb/stimulus-trix-error

javan commented 5 years ago

👋

This is a subtle timing issue that was fixed in https://github.com/stimulusjs/stimulus/pull/131, and will be released soon in Stimulus 1.1. In the meantime, you can work around it by waiting for the DOM to load before starting your controllers:

--- a/app/javascript/packs/application.js
+++ b/app/javascript/packs/application.js
@@ -12,4 +12,7 @@ import { definitionsFromContext } from "stimulus/webpack-helpers"

 const application = Application.start()
 const context = require.context("controllers", true, /.js$/)
-application.load(definitionsFromContext(context))
+
+addEventListener("DOMContentLoaded", () => {
+  application.load(definitionsFromContext(context))
+})