fs-heroes / fsh-website-comments

0 stars 0 forks source link

tutorials/stimulus/create-custom-events/ #4

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

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

happyplaygrounds commented 3 years ago

Well done. Like it! thx

davidromani commented 3 years ago

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

rhymes commented 3 years ago

@davidromani you have to use { detail: { count: response.data.count } }

see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent#example

leevigraham commented 1 week ago

Worth noting this is now baked in: https://stimulus.hotwired.dev/reference/controllers#cross-controller-coordination-with-events