Change Callback Not Firing as Expected
See original GitHub issueI’m new to the Stimulus library so apologies for the basic question. I have a controller with a version
value that is mutated by a radio button list in a form. When the value of the radio button changes, I change version
to what the user selected. Then I have a change callback function declared that executes the important logic I want to happen, in this case changing the image source for an img
tag. Currently, the change callback only fires the first time the controller is connected, but never again.
I have observed that the data attribute in the HTML is changing as expected, but the change callback function is only called the first time.
Controller Code
import { Controller } from "@hotwired/stimulus"
const imageMap = {
11: '...',
12: '...',
}
export default class extends Controller {
static targets = [ 'heroImage' ];
static values = { version: Number }
changeVersion(event) {
this.versionValue = Number(event.currentTarget.value);
}
versionValueChanged(version) {
this.heroImageTarget.src = imageMap[version]
}
}
HTML
<div
data-controller="pdp"
data-pdp-version-value="12"
>
<form>
<% (11..12).to_a.reverse.each do |v|
id = "#{v}th-gen"
%>
<div>
<input
type="radio"
id=<%= id %>
name="generation"
value=<%= v %>
data-action="change->pdp#changeVersion:prevent"
<%= v == 12 ? 'checked' : nil %>
>
<label for=<%= id %>><%= "#{v}th Generation" %></label>
</div>
<% end %>
</form>
<img
data-pdp-target="heroImage"
src="..."
/>
</div>
Any help or suggestions to fix this? I think I’m using the change callback as intended.
Issue Analytics
- State:
- Created a year ago
- Comments:6 (5 by maintainers)
Top GitHub Comments
@tleish and @marcoroth - I can confirm that the pen example does indeed work as expected. I’ve been testing in Chrome and Safari.
Interestingly, if I copy and paste in the controller code provided by @tleish in my local project, the change callback fires as expected with no changes to my HTML. I actually can’t spot a meaningful difference between my controller code and the controller code in the pen.
I just tried again locally with my original code and now it does seem to be working as the documentation describes. I’m not entirely sure what changed or why it’s working now, but it’s working enough to close the issue! Thanks for all the input everyone, it’s appreciated!
Awesome @arb, thanks for the feedback!