Skip to content

Conversation

adammiribyan
Copy link
Contributor

@adammiribyan adammiribyan commented Apr 22, 2020

I came across this method while reading through the javascript code of Hey, and have implemented it, along with the globally accessible ApplicationController, into a couple of projects already.

I'm only responsible for compiling this PR, credit goes to the folks behind Hey 💯

  1. It establishes an adequate event naming convention.
  2. It encapsulates the steps you'd have to take to define and emit a custom event into a single this.dispatch call.

Here's an simplified e-shop example:

import { Controller } from 'stimulus'

// cart_controller.js
export default class extends Controller {
  updateCart() {
    // Does stuff...
    this.dispatch('updated', { itemsCount })
  }
}

// cart_badge_controller.js
export default class extends Controller {
  static targets = [ 'counter' ]

  initialize() {
    document.addEventListener('cart:updated', this.refreshCounter.bind(this))
  }

  // Actions
  refreshCounter({ detail: { itemsCount } }) {
    this.counterTarget.innerText = itemsCount
  }
}

@tmrkp
Copy link

tmrkp commented May 18, 2020

The CustomEvent() constructor is not supported in some older Browsers. There is a small Polyfill (see mdn), which should be added to the polyfill package if this gets merged.

Base automatically changed from master to main January 12, 2021 20:57
@dhh
Copy link
Member

dhh commented Jun 14, 2021

This is great, @adammiribyan. Could you add some documentation for it as well?

@timrosskamp Support is available in all evergreen browsers, so think we're good there. Although I suppose it'd be nice to document the constraint: https://caniuse.com/?search=CustomEvent

@Sub-Xaero
Copy link
Contributor

It would also be nice to see this integrate with the new debug mode added in #354, to give some visibility of events firing whilst debugging.

@dhh dhh merged commit 7b84aff into hotwired:main Jul 1, 2021
@dhh
Copy link
Member

dhh commented Jul 1, 2021

Would be nice to get some tests added for this too, if someone wants to start a PR around that.

@seb-jean
Copy link
Contributor

I look forward to this feature :)

@brendon
Copy link

brendon commented Oct 15, 2021

In terms of attribution, this implementation seems pretty similar to: https://github.com/stimulus-use/stimulus-use/blob/main/docs/use-dispatch.md

I'm not sure which came first :) (#302 (comment))

EDIT: It looks like the stimulus-use version was also inspired by the Hey sourcecode: stimulus-use/stimulus-use#174 (comment) so that's settled :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

8 participants