Mithril & 'm' the magical function

artydev - Jul 14 '20 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player