Lifecycle Explorer

by barneycarroll

Level: beginner • Mithril.js Version: latest

This is an example that shows an interactive sandbox you can check the order of Mithril.js' lifecycle events for nested DOM structure. This is very helpful if you have a bunch of nested components and want to see in which order these components are created and ready for the application. The example is using all of Mithril.js` lifecycle methods.

Live Example

Dependencies

Type Name URL
scriptmithril@latesthttps://unpkg.com/mithril@latest

JavaScript

function Log() {
  let counter = 1
  let log = []
  let me = {
    add(message) {
      log.push({id: counter++, time: new Date(), message: message})
      return me
    },
    log() {
      console.log(log)
    },
    map(f) {
      return log.map(f)
    }
  }
  return me
}

var log = new Log()
//log.add('test 1').add('test 2')
//log.add('test 3')

App = {
  views: {}
}

App.views.Log = function () {
  let dom = undefined
  let me = {
    view: (vnode) => {
      //dom && setTimeout(render)
      return [
        m('button', {
            onclick: () => {
            }
          },
          'Redraw'
        ),
        m('button', {
            onclick: (e) => {
              e.redraw = false
              log = new Log()
              render()
            }
          },
          'Clear'
        ),
        m('button', {
          innerHTML: 'Break',
          onclick: (e) => {
            e.redraw = false
            log.add('***')
            render()
          }
        }),
        m('', {
          oncreate: (vnode) => {
            dom = vnode.dom
            render()
          },
          onupdate: () => render()
        }),
      ]
    }
  }
  return me
  function render() {
    m.render(dom, [
      m("span", ["Current time:", new Date().toString()]),
      log.map((it) => {
        return m('pre', JSON.stringify(it))
      })
    ])

  }
}

App.views.Node = function (vnode) {
  let key = vnode.attrs.key
  let subnodes = []
  return {
    oninit: (vnode) => {
      log.add(key + ' -- oninit')
    },
    oncreate: (vnode) => {
      log.add(key + ' -- oncreate')
    },
    onupdate: (vnode) => {
      log.add(key + ' -- onupdate')
    },
    onbeforeupdate: (vnode) => {
      log.add(key + ' -- onbeforeupdate')
    },
    onbeforeremove: (vnode) => {
      log.add(key + ' -- onbeforeremove')
    },
    onremove: (vnode) => {
      log.add(key + ' -- onremove')
    },
    view: ({
             tag,
             attrs: {remove},
             output,
           }) => {
      log.add(key + ' -- view (start)')
      let retVnode = m('[style=border: 1px solid; padding: .5em; margin: .5em]', {}, [
        'Node',
        key,
        ' ',
        remove && m('button', {
          innerHTML: 'x',
          onclick: remove,
        }),
        m('hr'),
        subnodes.map((key, i) =>
          m(tag, {
            key,
            remove: () =>
              subnodes.splice(i, 1),
          })
        ),
        m('button', {
          innerHTML: '+',
          onclick: () =>
            subnodes.push(key + '.' + (subnodes.length + 1))
        }),
      ])
      //setTimeout(() => {
      log.add(key + ' -- view (end)')
      //})
      return retVnode
    }
  }
}

m.mount(document.body, {
  view() {
    return [
      m('[style=flex: 0 1 50%; overflow-y: auto;]', m(App.views.Node, {key: 1})),
      m('[style=flex: 1 1 50%; overflow-y: auto;]', m(App.views.Log))
    ]
  }
})

As a prerequisite for this snippet, the latest version of Mithril.js framework is required. Beginners should have no problems following this example, that simply shows some basic recipies.

Here we can see use cases of different Mithril.js API methods like m.render or m.mount, besides the centrepiece m() hyperscript function. Moreover, it can also be seen how lifecycle methods (as known as hooks) like onbeforeupdate, onremove, onbeforeremove, onupdate, oncreate and oninit can be used. Also covered in this example is the use of Vnodes or virtual DOM nodes, a JavaScript data structure that describes a DOM tree.

The example was written by barneycarroll, last edits were made on 23 October 2021. The author has contributed some more snippets. Click here to see them all.

Contribute

Did you note a typo or something else? So let me know by opening an issue. Or much better: just fork the repository on GitHub, push your commits and send a pull request. Ready to start your work? Then click on the edit link below. Thanks in advance!

See more code examples  •  Edit this example on GitHub