DEV Community

artydev
artydev

Posted on

Mithril & 'm' the magical function

Imagine a 'magical' function, let us name it 'm'.
This function would allow to create DOM Nodes, no big surprise
there are plenty ways to create DOM Nodes

In fact 'm' would create 'Virtual Nodes' or 'Vnodes'.

The nice tricks with 'm' is that it would allow to write vnodes like this:

let myelt = m("div.one.two", {onclick: () => alert("I am alive")}, "Elt 1")

Or, if you prefer

let myelt2 = m("div", 
    {
     class: "one two",
     onclick: () => alert("I am alive")
    }, "Elt 2")

You will agree with me that there is no fancy tricks here.
'm' is just a function taking as parameters :

  • a tag name
  • an optional object containing properties
  • a text (or a list of vnodes)

Imagine now, that we create a new method on 'm' in order to attach our vnodes to the 'real' DOM, let us call it 'mount'.

So we have now two functions at our disposal :

  • m
  • m.mount

m.mount would take two argument :

  • a target to append our vnode
  • an object containing a method called 'view' which would return a vnode

I know the second argument is a little tricky. But stay with me, you will discover its power later :-)

So know we can write

const MyVnode  = m("div.one.two", {onclick: () => alert("I am alive")}, "My first  vnode")

m.mount(document.body, {
  view: () =>  MyVnode
})

It is time know to say that this magical function exists, and it is provided by the great library Mithril.

In an other post, we will create the famous 'Todo List'.
An we will only use the two functions presented above.

For now you can test what we have acomplished so far :

MyFirstVnode

Top comments (2)

Collapse
 
mxldevs profile image
MxL Devs

I like the library simply because it's called "Mithril" although I have no idea what the purpose of a "virtual node" is. Just inserting elements into the DOM tree on-the-fly?

Collapse
 
artydev profile image
artydev • Edited

Hy,
The majority of frontend librairies don t modify the DOM directly
They create a representation of the real DOM called virtual DOM
They make a diff between those and patch the real DOM accordingly.
Vnodes are attached to the Virtual DOM
Regards