Best practice use data in javascript (thus passing data)

Haven’t found a topic on the elixir forum regarding this, only on stackoverflow. If it exists already, please point me in the right direction and I’ll delete this post. Because the response was limited, I was wondering if the Phoenix experts here could provide their opinions regarding passing data from the controller to your JS.

A use case that I’m facing now:
Building a timeline-ish feature with an edit page. On the edit page, i want to let the user upload images asynchronously. (so that if they edit something in the text field, the explanation on the timeline, and then upload an image it doesn’t need to refresh) But I need the article id to make the asynchronous call.

As far as i know there are 2 options:

  • work with data attributes (link)
  • put a tag in your template, and assign a variable where you put your json encoded (elixir) variable so that you can access it in your javascript.

This is a problem with multiple frameworks, and I’d be truly happy if some sort of best-practice could be formed.

Thank you in advance!

I prefer to pass data to js with data attributes, it’s easy.

I have something like this in my template

<div 
  id="app" 
  data-src="<%= display_path @picture, :large %>"
  data-id="<%= @picture.id %>"
  data-token="<%= @token %>"></div>

and I retrieve like this in app.js.

const root = document.getElementById('app');
if (root) {
  const { src, id, token } = root.dataset;
  console.log(src, id, token);
}
4 Likes