Component External State Counter & Entries

by osban

Level: beginner • Mithril.js Version: latest

This is an example showing a very simple Component and a simple Pojo for state management. In this case the model for state management is a global variable. The example is a variant of the classic counter, that shows a count value together with a list of entries. By clicking a button the counter will increase and a new entry will be appended to the list. Handling status with global variables works, but for the sake of clarity it only makes sense in very simple projects.

Live Example

Dependencies

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

JavaScript

const model = {
  count: 0,
  entries: []
}

const test = () => {
  const update = () => {
    model.count++
    model.entries.push(model.count + " - " + new Date())
  }

  return {
    view: () =>
      m('div',
        m('h1', "Test"),
        m('button', {onclick: update}, "CLICK"),
        m('h2', `Number of clicks: ${model.count}`),
        model.entries.map(x => m('div', x))
      )
  }
}

m.mount(document.body, test)

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.

In this code sample Mithril.js' m.mount API method is use, besides the basic hyperscript function m().

The example was written by osban, last edits were made on 24 September 2020. 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