Skip to content

Instantly share code, notes, and snippets.

@frahugo
Last active September 21, 2022 19:27
Show Gist options
  • Save frahugo/37e1e6881d285445889e2306cfcb5a88 to your computer and use it in GitHub Desktop.
Save frahugo/37e1e6881d285445889e2306cfcb5a88 to your computer and use it in GitHub Desktop.
Experiment mixing DataTable and a global LiveView outside of table (as issues occurs when having liveview in each row of the table - duplicate phx-ids detected)
config :gccg_web, GccgWeb.Withdrawals.OutflowStateLive,
pubsub_subscriptions: [
GccgCore.Accounts.WorkflowApplicationService
]
= live_render(@conn, GccgWeb.Withdrawals.OutflowStateLive)
= for outflow <- @outflows do
tr data-id=outflow.id data-state=outflow.state data-soon=soon?(outflow)
td data-type="outflow-state"
= state_label(outflow.state)
= if outflow.state == :upcoming do
a.btn.btn-sm.btn-outline-primary data-click-event="flag_as_pending" data-click-id=outflow.id
| Pending
Hooks.OutflowState = {
mounted() {
$('[data-click-event]').click((e) => {
let event = $(e.target).data('click-event');
let id = $(e.target).data('click-id');
this.pushEvent(event, {id: id})
})
},
}
defmodule GccgWeb.Withdrawals.OutflowStateLive do
@moduledoc false
use GccgWeb, :live_view
import GccgWeb.LiveViewHelpers
on_mount GccgWeb.Live.UserAuth
@impl true
def mount(_params, session, socket) do
query = GivernyEx.Module.get!(session, "query", GccgWeb.Workflow.ActiveActionQuery)
socket =
socket
|> subscribe_to_event_publishers(__MODULE__)
|> assign(query: query)
{:ok, socket}
end
@impl true
def render(assigns) do
~H"""
<div id="outflow-state-live-view" phx-hook="OutflowState"></div>
"""
end
@impl true
def handle_event("flag_as_pending", %{"id" => outflow_id} = _params, socket) do
Phoenix.PubSub.broadcast(
GccgCore.PubSub,
"GccgCore.Accounts.WorkflowApplicationService",
{:outflow_now_pending, outflow_id}
)
socket
|> noreply()
end
def handle_info({:outflow_now_pending, outflow_id}, socket) do
socket
|> push_event("outflowStateChanged", %{outflow_id: outflow_id, state: "Pending"})
|> noreply()
end
end
var table = $('#outflows-list').DataTable({...});
window.addEventListener(`phx:outflowStateChanged`, (e) => {
let el = $('[data-id=' + e.detail.outflow_id + ']')[0];
if (el) {
let rowData = table.row(el).data();
rowData[0] = e.detail.state;
table.row(el).data(rowData).draw();
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment