and (
Let’s work through an example of how to integrate this with JSON data provided by the (LiveView) server. We’ll send some static data from the backend in response to an event, but this data could come from any source.
The following will assume you’ve set up a Phoenix project using .
Within a callback like mounted, the hook sends events to the backend using this.pushEvent, and handles events from the server by registering a handler for a particular event name using this.handleEvent.
It’s important to note only one hook is permitted per element, so you only need to reason about one stream of events between client and server.
With that knowledge in mind - let’s define a JsonView hook that registers an event handler, that eventually calls jsonview.render on the element to render the tree of data.
import { Socket } from 'phoenix';
import jsonview from '@pgrabovets/json-view';
const JsonViewHook = {
mounted() {
this.handleEvent("render_json", ({ data }) => {
this.el.innerHTML = "";
const tree = jsonview.create(data);
jsonview.render(tree, this.el);
});
}
}
const liveSocket = new LiveSocket(
"/live",
Socket,
{hooks: { JsonView: JsonViewHook }, ...}
);
...
We do several things in these several lines of code:
- We define a
JsonViewHookobject with amountedfunction. This function will be called when the element with this hook is mounted in the DOM. - Inside
mounted, we set up an event listener for a custom event called "render_json". This event will be triggered from our LiveView. - When the event is received, it expects a
dataparameter containing the JSON to be rendered. - We clear the existing content of the element.
- We use
jsonview.createandjsonview.renderto render the JSON data into our element.
To use this hook - we’ll just need to add the phx-hook attribute with the name of the hook (”JsonView”) to an element:
<div id="json-container" phx-hook="JsonView"></div>
Sending events to the server
We’ll just need to trigger an event from the backend to provide this data. We’ll leave this outside the scope of this article for now - perhaps a button could trigger an event to the backend? - but you could use this.pushEvent from the mounted hook like so:
mounted() {
this.pushEvent("send_json", {});
}
to send an event to the LiveView server that can be handled with handle_info. is the way to push an event from LiveView to the browser. It can be called at any point - including in mount - though a good practice is to ensure that the page and all its elements are in a known state before sending these events. Otherwise - you’ll have events silently being dropped during page setup - a sure route to unpredictability!
Let’s write a handle_event clause for an event we might receive from the client, which pushes an event to the client:
def handle_event("send_json", _params, socket) do
{:noreply, push_event(socket, "render_json", %{data: [1, 2, 3]})}
end
That’s it! And there’s flexibility here too. Registering event handlers with names on both the client and the server marks a clear separation between the handling of the event and how the event is raised.
Further integration
We’ve seen a simple example of the integration between client and server. A common extension of this would be to scope certain updates to certain elements, through the use of event parameters and element attributes. This helps to reduce the amount of unnecessary events and handler work.
This event handling can also be expanded for tighter client-side library integration with the backend. For example, typically these Javascript libraries emit higher-level user interaction events. Our library example, json-view, doesn’t do this, but a charting library like chart.js does.
However, from a user interaction standpoint, a round-trip to the server for processing should be generally avoided. Typically, any rendering update based on events would be handled by the rendering library client-side.
But capturing user activity for other reasons is a common use case. This includes monitoring, logging and analysis. These don’t require a response, so pushEvent from within a hook can be ideal for this type of asynchronous processing on the server.
Conclusion
Integrating powerful Javascript client-side libraries that require control over the DOM is a key part of creating rich, dynamic user interfaces. Not all page updates need to be real-time, and so retaining LiveView offers a powerful yet simple way to continue to control other page state.
Becoming familiar with LiveView hooks and their associated events makes integrating these with data that originates from the server possible. It’s also important to note that not all user interactivity require a round-trip to the server, and the interfaces you build will be more flexible and responsive when you use powerful Javascript libraries.
SOCIAL SHARE CARD GENERATOR