Data Binding Helper

by osban

Level: beginner • Mithril.js Version: latest

Here we have a nice little example using a data binding helper function. This function makes data binding very easy by just including the binder in the view method of the component.

Live Example

Dependencies

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

JavaScript

const model = {
  first: 'Joe',
  last: 'Black',
  email: 'joe@black.com',
  color: 'red'
}

const binder = model => ({
  onchange: e => {
    model[e.target.name] = e.target.value
  }
})

const app = {
  view: () => [
    m("div", binder(model),
      m("input", {name: 'first', value: model.first}),
      m("input", {name: 'last',  value: model.last}),
      m("input", {name: 'email', value: model.email}),
      m('select', {name: 'color'},
        ['orange','blue','red','green']
        .map(c => m('option', {selected: c === model.color}, c))
      )
    ),
    m('pre', JSON.stringify(model, null, 2))
  ]
}

m.mount(document.body, app)

The snippet is using the most current version of Mithril.js framework. It is aimed at beginners and shows some basic recipes.

In addition to the Mithril.js hyperscript function m(), here we can see an example of Mithril.js' m.mount API method.

The example was contributed by osban and last modified on 24 September 2020. Click here to see more examples contributed by the author.

Contribute

If anyone has some improvements, that should be addressed, let me know by opening an issue. Or simply fork the repository on GitHub, push your commits and send a pull request. For starting your work, you can click the edit link below. Thanks for contributing.

See more code examples  •  Edit this example on GitHub