From be3cb9a7bbd053334ebc785da63137bff60d5851 Mon Sep 17 00:00:00 2001 From: Kelvin Stinghen Date: Wed, 12 May 2021 14:31:54 -0300 Subject: [PATCH] Allowing to use node elements as the `target` on `pushEventTo` (#1397) * Allowing to use `this.el` on `this.pushSendEvent` Closes #1396 * Fixing the variable name for target It's supposed to be `phxTarget`, not `target` * Using `instanceof HTMLElement` to check if `phxTarget` is a DOM node * Documenting `pushEventTo` --- assets/js/phoenix_live_view.js | 4 ++++ guides/client/js-interop.md | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/assets/js/phoenix_live_view.js b/assets/js/phoenix_live_view.js index fc6fa5bfe..edf00ad5e 100644 --- a/assets/js/phoenix_live_view.js +++ b/assets/js/phoenix_live_view.js @@ -2114,6 +2114,10 @@ export class View { } withinTargets(phxTarget, callback){ + if(phxTarget instanceof HTMLElement) { + return this.liveSocket.owner(phxTarget, view => callback(view, phxTarget)) + } + if(/^(0|[1-9]\d*)$/.test(phxTarget)){ let targets = DOM.findComponentNodeList(this.el, phxTarget) if(targets.length === 0){ diff --git a/guides/client/js-interop.md b/guides/client/js-interop.md index 06d5fc990..1f57c8d55 100644 --- a/guides/client/js-interop.md +++ b/guides/client/js-interop.md @@ -145,7 +145,10 @@ The above life-cycle callbacks have in-scope access to the following attributes: * `viewName` - attribute matching the DOM node's phx-view value * `pushEvent(event, payload, (reply, ref) => ...)` - method to push an event from the client to the LiveView server * `pushEventTo(selectorOrTarget, event, payload, (reply, ref) => ...)` - method to push targeted events from the client - to LiveViews and LiveComponents. + to LiveViews and LiveComponents. It sends the event to the LiveComponent or LiveView the `selectorOrTarget` is + defined in, where it's value can be either a query selector or an actual DOM element. If the query selector returns + more than one element it will send the event to all of them, even if all the elements are in the same LiveComponent + or LiveView. * `handleEvent(event, (payload) => ...)` - method to handle an event pushed from the server For example, the markup for a controlled input for phone-number formatting could be written