Instead of selecting the controller, send an event handled by stripe-cards

Using a query selector to find controller in order to call method could be dangerous as the DOM can change. Using an event should be more robust.
This commit is contained in:
Jean-Baptiste Bellet
2023-01-18 11:40:28 +01:00
parent d2e6b7d164
commit 7320a1714c
3 changed files with 12 additions and 12 deletions

View File

@@ -1,4 +1,4 @@
%div{"data-controller": "stripe-cards"}
%div{"data-controller": "stripe-cards", "data-paymentid": "#{payment_method.id}" }
- if @saved_credit_cards.any?
.checkout-input
%label

View File

@@ -12,17 +12,12 @@ export default class extends Controller {
selectPaymentMethod(event) {
this.setPaymentMethod(event.target.dataset.paymentmethodId);
const stripeCardSelector =
this.application.getControllerForElementAndIdentifier(
document
.querySelector(
`[data-paymentmethod-id="${event.target.dataset.paymentmethodId}"]`
)
.querySelector('[data-controller="stripe-cards"]'),
"stripe-cards"
);
stripeCardSelector?.initSelectedCard();
// Send an event to the right (ie. the one with the same paymentmethodId)
// StripeCardsController to initialize the form elements with the selected card
const customEvent = new CustomEvent("stripecards:initSelectedCard", {
detail: event.target.dataset.paymentmethodId,
});
document.dispatchEvent(customEvent);
}
setPaymentMethod(paymentMethodContainerId) {

View File

@@ -7,6 +7,11 @@ export default class extends Controller {
connect() {
this.initSelectedCard();
document.addEventListener("stripecards:initSelectedCard", (e) => {
if (e.detail == `paymentmethod${this.element.dataset.paymentid}`) {
this.initSelectedCard();
}
});
}
initSelectedCard() {