Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevenchanin/d6576dd4f8cdd99b2c1671bda2478048 to your computer and use it in GitHub Desktop.
Save stevenchanin/d6576dd4f8cdd99b2c1671bda2478048 to your computer and use it in GitHub Desktop.
Actions not firing on dynamically added content
Hitting a problem that actions aren't firing from markup dynamically added inside a controller with `insertAdjacentHTML`. Wondering if anyone has any suggestions?
Details:
We have a controller that lets the user edit the heights of air conditioners on a roof (its for a solar panel app). For each air conditioner, we have an "air conditioner div" that has has a target ("heightContainer") and an input with an action ("input->heights-form#updateHeight").
The air conditioner div looks like:
```
.form-group.col-6{ data: { layout_editor__air_conditioner_heights_form_target: "heightContainer", uuid: ac.uuid }}
%div{ class: class_names('field_with_errors': ac.height.blank?), data: { identifier: 'fieldWrapper' } }
- id = "height_#{ac.uuid}"
%label{ for: id } Air Conditioner ##{ac.identifier}
.input-group
= text_field_tag :height, ac.height, class: 'form-control', id: id,
data: { action: 'layout-editor--ac-heights-form#updateHeight',
layout_editor__ac_heights_form_uuid_param: ac.uuid }
.input-group-append
.input-group-text FT
```
When they edit the height in the input, `updateHeight` fires.
For the initial server rendered divs inside the controller, everything works.
When the user draws a new air conditioner, want to add a new div inside the controller. We do that by`
* when we create the page, we render a blank "air conditioner div" and stick it on the controller as a value property
```
:ruby
blank_element = capture do
render("/layout_editor/air_conditioners/air_conditioner_height_element",
ac: AirConditioner.new(identifier: '[identifier]', uuid: '[uuid]'))
end
.row{ data: { controller: 'layout-editor--air_conditioner-heights-form',
layout_editor__air_conditioner_heights_form_height_element_template_value: blank_element }}
```
* we take that div and insert it at the bottom of the list
```
const template = this.heightElementTemplateValue
.replaceAll("[identifier]", air_conditioner.identifier)
.replaceAll("[uuid]", air_conditioner.uuid);
this.element.insertAdjacentHTML("beforeend", template)
```
1) We can see the newly inserted div in `this.heightContainerTargets` (so it seems like Stimulus is noticing that something has been added), but
2) when the user types in a height, it doesn't fire `updateHeight`. If we save and refresh the page, then the element is rendered on the server and the stimulus action works.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment