DEV Community

artydev
artydev

Posted on

VanJS : Revisiting displaying JSON

Beware, the 'autoappend' functionality from Eckehard is in pull-requests in github repository.

So let's see how we can rewrite our previous example.

You can easily see that the code is plain vanilla JS.
There is no templates, JSX, directives.

All the code execute directly in Browser, whitout any ceremony.

Demo

<fetch-user data-num="5">
  <a href="https://randomuser.me/api/">Random Users</a>
</fetch-user>
Enter fullscreen mode Exit fullscreen mode
import van from "./van.js"

const { div, button, span, "user-card": UserCard, img } = van.tags
const { end, begin } = van

const bdiv = () => begin(div());
const btn = button

function Card(user) {
  let
    thumbnail = user.picture.thumbnail,
    user_name = user.name.first,
    user_email = user.email,
    user_city = user.location.city;

  let user_card = begin(UserCard())
    // identity
    div({ class: 'ident' },
      img({ src: thumbnail }),
      div({ style: 'text-align:center' },
        user_name
      )
    )
    // address
    div({ class: 'address' },
      div(user_email),
      div(user_city),
    )

    btn (
      {
        onclick: () => alert(`Hy, I am ${user_name}`),
      }, "Hy"
    )

  end()
  return user_card
}

function Users(users) {
  console.log(users)
  return users.map(Card)
}

class FetchUser extends HTMLElement {
  async connectedCallback() {
    let numusers = Number(this.dataset.num)
    let link = this.querySelector("a");
    let req = await fetch(`${link.href}?results=${numusers}`)
    let resp = await req.json()
    van.add(this, Users(resp.results))
  }
}

customElements.define("fetch-user", FetchUser);  
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
efpage profile image
Eckehard • Edited

So, there will be an addOn to VanJs, that adds the DML core functionality transparently to VanJS. This is called van_dml.js and needs simply to be appended after VanJS like this.

  <script src="van-0.11.10.nomodule-min.js"></script>
  <script src="van_dml.js"></script>
Enter fullscreen mode Exit fullscreen mode

Code needs still to be tested to run with vite/rollup.

Collapse
 
artydev profile image
artydev • Edited

Great Eckehard
I am very glad to see you makes now part of this amazing project.
and sure your addition will be appreciate by many VanJS users :-)