From 71b87bfc0b39551e5638836143b17a8a0431d7e9 Mon Sep 17 00:00:00 2001 From: f Date: Sat, 18 May 2024 18:03:01 -0300 Subject: [PATCH] feat: poder abrir el modal con un evento --- .../controllers/modal_controller.js | 19 +++++++++++++++++++ app/views/posts/attributes/_new_has_many.haml | 3 ++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/app/javascript/controllers/modal_controller.js b/app/javascript/controllers/modal_controller.js index 3a614b80..011c1254 100644 --- a/app/javascript/controllers/modal_controller.js +++ b/app/javascript/controllers/modal_controller.js @@ -3,8 +3,27 @@ import { Controller } from "stimulus"; export default class extends Controller { static targets = ["modal", "backdrop"]; + // TODO: Stimulus >1 + connect() { + this.showEvent = this.show.bind(this); + + window.addEventListener("modal:show", this.showEvent); + } + + // TODO: Stimulus >1 + disconnect() { + window.removeEventListener("modal:show", this.showEvent); + } + + /* + * Podemos enviar la orden de apertura como un click o como un + * CustomEvent incluyendo el id del modal como detail. + */ show(event = undefined) { event?.preventDefault(); + const modalId = event?.detail?.id; + + if (modalId && this.element.id !== modalId) return; this.modalTarget.style.display = "block"; this.backdropTarget.style.display = "block"; diff --git a/app/views/posts/attributes/_new_has_many.haml b/app/views/posts/attributes/_new_has_many.haml index f8ec89d4..76cf299f 100644 --- a/app/views/posts/attributes/_new_has_many.haml +++ b/app/views/posts/attributes/_new_has_many.haml @@ -4,8 +4,9 @@ id = "#{base}_#{attribute}" name = "#{base}[#{attribute}][]" form_id = "form-#{Nanoid.generate}" + modal_id = "modal-#{Nanoid.generate}" -%div{ data: { controller: 'modal array', 'array-original-value': metadata.value.to_json, 'array-new-array-value': site_posts_new_related_post_path(site) } } +%div{ id: modal_id, data: { controller: 'modal array', 'array-original-value': metadata.value.to_json, 'array-new-array-value': site_posts_new_related_post_path(site) } } .form-group = hidden_field_tag name, '' = label_tag id, post_label_t(attribute, post: post)