Phoenix_live_view: Question: Is there a simple JavaScript escape hatch for manually triggering LiveView events?

Created on 7 May 2019  路  9Comments  路  Source: phoenixframework/phoenix_live_view

What I'm doing

Using the browser drag and drop API to order a list: https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API

What I think I need

To write sprinkles of JavaScript that will trigger LiveView events from the drag and drop events.

Looks sort of like this

content_tag :tr, [
  draggable: "true",
  ondragover: "Dragdrop.dragover(this, event)",
  ondrop: "Dragdrop.drop(this, event)",
  data: [id: id],
] do
  # inner content
end

With this dirty JavaScript:

class DragdropManager {
  dragover(destinationElement, event) {
    event.preventDefault()
    // TODO: trigger LiveView event
  }

  drop(sourceElement, event) {
    event.preventDefault()
    // TODO: trigger LiveView event
  }
}

window.Dragdrop = new DragdropManager()

But what I'd need to finish out are some docs (or maybe a pointer in comments) on how to get a JavaScript handle to the mounted LiveView and then manually send an event to it.

Most helpful comment

Does anyone know is there's any movement on the public API for this?

All 9 comments

Not yet, but it's on the roadmap and isn't far off. Thanks!

To answer my own question, after reading the source and experimenting, I discovered you can do something like this:

function pushLiveViewEvent(liveSocket, element, event, value = "") {
  liveSocket.owner(element, (view) => view.pushWithReply("event", {
    type: "event",
    event,
    value,
  }))
}

Note that is a private API, so you shouldn't rely on it

Understood. Keeping myself pinned to a commit until the real API ships.

Does anyone know is there's any movement on the public API for this?

Hello, sir @chrismccord, Is it possible for you to tell about any movement for creating Drag and Drop API in Phoenix LiveView? because you said

Not yet, but it's on the roadmap and isn't far off. Thanks!

Thank you for all your efforts.

@shahryarjb There's the public push event methods now: https://hexdocs.pm/phoenix_live_view/0.12.0/Phoenix.LiveView.html#module-js-interop-and-client-controlled-dom

@shahryarjb For drag and drop check out that same link (see Hooks). Checkout my code here: https://github.com/alecho/live_chess/blob/master/assets/js/app.js#L26

@alecho at first I want to say, thank u. yes but it is fine for somebody who knows JS. not me that do not know even 1 word of Js :((
I thought we can create a drag and drop html without any js code.

Was this page helpful?
0 / 5 - 0 ratings