[Solved] Stimulus controller cannot access `element.editor` after v2.0.0-beta.1
- Dominant language
- JavaScript
- Stars
- 20k
- Forks
- 1.1k
- Avg merge
- 3d 12h
- Merged PRs (30d)
- 13
Description
I'm using Trix in a Rails/webpacker app to give users a nice-looking WYSIWYG when generating PDF documents. In particular, users can insert references (implemented following [Chris Oliver's tutorial](https://gorails.com/episodes/at-mentions-with-actiontext)) whose value gets calculated when viewing the PDF document.
Since Trix version `2.0.0-beta.1`, my stimulus controller can no longer access `this.element.editor` when connecting, which returns `undefined`. I'm guessing this happened after changing how Trix gets started (in #1008)?
Calling `document.getElementById('#trix-editor').editor` works from a browser console, so I guess it's just that the Stimulus controller is attached before Trix has been applied to the base element.
I've tried calling `Trix.start()` at various steps, but that makes the JS crash, even if I disable chunking in webpacker config.
I found a workaround while researching this issue, see below.
##### Steps to Reproduce
```js
// app/assets/javascripts/packs/application.js
import Trix from "trix"
document.addEventListener("trix-before-initialize", () => {
// I18n config
})
import("controllers")
```
```js
// app/assets/javascripts/controllers/placeholder_controller.js
import { Controller } from "@hotwired/stimulus";
import Trix from "trix"
export default class extends Controller {
connect() {
this.editor = this.element.editor // -> undefined after 2.0.0-beta.1
}
}
```
##### Solution
I was able to work around this by calling `this.element.editor` dynamically when interacting with the controller, instead of storing it when it is connected.
```js
export default class extends Controller {
connect() {
// Don't store a reference to this.element.editor
}
get editor() {
return this.element.editor
}
}
```
##### Details
* Trix version: 2.0.4
* Browser name and version: Firefox 108.0.1
* Operating system: MacOS Monterey 12.6.2
Contributor guide
No contributing guide indexed for this repository
Research direction
Start with the reproduction in app/assets/javascripts/packs/application.js and app/assets/javascripts/controllers/placeholder_controller.js, then reproduce the timing difference between Stimulus connect() and Trix initialization. Compare the stored reference with the dynamic editor getter workaround; done would require a confirmed fix or documented lifecycle behavior, but the issue provides no test file or specific desired change.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- frontend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100