Created
March 8, 2021 21:25
-
-
Save jorgegorka/7fa359ccc5fc06a25e3af82925db4a2f to your computer and use it in GitHub Desktop.
Stimulus.js send message to parent controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body data-controller="outer"> | |
... | |
<!-- Some newly inserted targets: --> | |
<div data-target="outer.thing" data-controller="inner">1...</div> | |
<div data-target="outer.thing" data-controller="inner">2...</div> | |
</body> | |
Each target has its own inner controller, which emits an inner-connected event when connected: | |
// inner_controller.js | |
export default class extends Controller { | |
connect() { | |
const event = document.createEvent("CustomEvent") | |
event.initCustomEvent("inner-connected", true, true, null) | |
this.element.dispatchEvent(event) | |
} | |
} | |
Add a data-action to the body element to call the thingConnected() method in response to those events: | |
<body data-controller="outer" data-action="inner-connected->outer#thingConnected"> | |
... | |
// outer_controller.js | |
export default class extends Controller { | |
static targets = [ "thing" ] | |
thingConnected(event) { | |
console.log(event.target) // the element that was just connected | |
} | |
} | |
https://github.com/hotwired/stimulus/issues/200#issuecomment-434731830 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment