Phoenix LiveView is a powerful framework built on Elixir, and offers an innovative approach to building real-time web interfaces without the need for extensive Javascript.
However, integrating with existing client-side libraries, like those for graphing, visualisation or rendering, can sometimes prove a challenge.
In this article, we’ll explore how we can integrate Phoenix LiveView with Javascript libraries that render to the DOM directly.
We’ll come across hooks, which allow us to run Javascript on certain lifecycle elements for a given element, and how these hooks enable streams of events (using push_event in LiveView and pushEvent in Javascript) to allow bi-directional real-time communication between client and server.
Background
TLDR: In Phoenix LiveView, you can use hooks and push_event to push data, and have the client-side library handle the rendering.
json-view (demo) - which displays JSON objects on a webpage as a tree that can be expanded and collapsed - is a good example of how some client-side Javascript libraries take control of rendering to the DOM and interaction with it.
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 mix phx.new, with LiveView enabled.
Library setup
There are multiple ways to incorporate a Javascript package as part of the page’s Javascript.
Recommending a preferred setup is outside the scope of this article, but there are two main ways:
- assets/vendor - in the typical LiveView project template, topbar is placed in this directory and included in the assets/app/app.js entrypoint file. This is suitable for smaller, more stable libraries in general, particularly if a single file version of the library is provided.
- NPM/Yarn - esbuild and webpack can pack referenced node_modules file into a single distribution file. This is suitable for larger, more complex libraries that change more frequently.
The problem with json-view
There are two incompatible models of rendering when we try to combine the two libraries.
LiveView follows the declarative model - you design the view, determine what data should be displayed, and LiveView works out which elements of the page need to change when the underlying data is changed.
It achieves this by using socket assigns in render:
def render(assigns) do ~H""" <p>Hello <%= @name %></p> """ end
However, libraries like json-view work on the imperative model. We specify the steps required to display the data in Javascript, outside the layout of the DOM itself:
import jsonview from '@pgrabovets/json-view'; const data = '{"name": "json-view", "version": "1.0.0"}' const tree = jsonview.create(data); jsonview.render(tree, document.querySelector('.tree'));
These two models are at odds. We have seemingly no way to match up the two methods of rendering data (declarative and imperative), but we need libraries like json-view to render rich interfaces on the client.
Fundamentally - we need to run Javascript code when the server prompts a change of page state. Let’s take a look at hooks, which helps to reconcile these two rendering models.
Hook setup
In LiveView, hooks are the way to provide bidirectional communication between the (browser) client and (LiveView) server, with the core object of communication being the event.
Hooks are defined in the LiveSocket and attached to an element using the phx-hook attribute. There are a number of callbacks - but we’ll focus on the mounted callback, since we can co-ordinate everything else via events. You can supply callbacks for other life-cycle events too - check the docs.
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 JsonViewHook object with a mounted function. 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 data parameter containing the JSON to be rendered.
- We clear the existing content of the element.
- We use jsonview.create and jsonview.render to 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> <h2> Sending events to the server </h2> <p>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:<br> </p> <pre class="brush:php;toolbar:false">mounted() { this.pushEvent("send_json", {}); }
to send an event to the LiveView server that can be handled with handle_info. The relevant section of the LiveView documentation covers more possibilities with this.pushEvent, including a scenario where a handler function can be specified to handle a reply payload directly.
Sending events from the server
push_event/3 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 render(assigns) do ~H""" <p>Hello <%= @name %></p> """ 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.
The above is the detailed content of Phoenix LiveView, hooks and push_event: json_view. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

JavaScript array built-in methods such as .map(), .filter() and .reduce() can simplify data processing; 1) .map() is used to convert elements one to one to generate new arrays; 2) .filter() is used to filter elements by condition; 3) .reduce() is used to aggregate data as a single value; misuse should be avoided when used, resulting in side effects or performance problems.

JavaScript's event loop manages asynchronous operations by coordinating call stacks, WebAPIs, and task queues. 1. The call stack executes synchronous code, and when encountering asynchronous tasks, it is handed over to WebAPI for processing; 2. After the WebAPI completes the task in the background, it puts the callback into the corresponding queue (macro task or micro task); 3. The event loop checks whether the call stack is empty. If it is empty, the callback is taken out from the queue and pushed into the call stack for execution; 4. Micro tasks (such as Promise.then) take precedence over macro tasks (such as setTimeout); 5. Understanding the event loop helps to avoid blocking the main thread and optimize the code execution order.

Event bubbles propagate from the target element outward to the ancestor node, while event capture propagates from the outer layer inward to the target element. 1. Event bubbles: After clicking the child element, the event triggers the listener of the parent element upwards in turn. For example, after clicking the button, it outputs Childclicked first, and then Parentclicked. 2. Event capture: Set the third parameter to true, so that the listener is executed in the capture stage, such as triggering the capture listener of the parent element before clicking the button. 3. Practical uses include unified management of child element events, interception preprocessing and performance optimization. 4. The DOM event stream is divided into three stages: capture, target and bubble, and the default listener is executed in the bubble stage.
