Open utterances-bot opened 3 years ago
Well done. Like it! thx
Thanks for you information, but what about to pass data inside CustomEvent? I'm tryed and on the Stimulus controller that catched the event it seems that doesn't works...
// trigger
const event = new CustomEvent('update-wishlist-counter', {count: response.data.count});
window.dispatchEvent(event);
// HTML node
<li data-controller="wishlist-counter" data-action="update-wishlist-counter@window->wishlist-counter#updateCounter">
(...)
</li>
// Stimulus controller
import { Controller } from 'stimulus';
export default class extends Controller {
static targets = ['counter'];
static values = {
counter: Number
}
updateCounter(event) {
console.log('[WishlistCounter::updateCounter] event catched', event);
this.counterTarget.innerText = event.count;
}
}
event.count is undefined
@davidromani you have to use { detail: { count: response.data.count } }
see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent#example
Worth noting this is now baked in: https://stimulus.hotwired.dev/reference/controllers#cross-controller-coordination-with-events
Communicating between Stimulus controllers using custom events
One of the challenging things about Stimulus is communication between different Stimulus controllers. Custom events makes it easy and intuitive
https://fullstackheroes.com/stimulusjs/create-custom-events/?utterances=27a6594ec25ad21362794127J4c6UWe%2Fk87FcLOFoCj2Fonqe4rDgLAycTM4%2B3DVrx%2FbOEAqofngnqsgmGKYStKi9T8uQQmOWaHl99dN1XivPSmhnaEUTS13C41vSrCfIb4ss7pr6BdUu%2BnU5%2Fs%3D