Skip to content

Instantly share code, notes, and snippets.

@Bondifrench
Forked from gilbert/example.js
Created August 2, 2016 21:26
Show Gist options
  • Save Bondifrench/4f39c9a6d445e264db0020212163698b to your computer and use it in GitHub Desktop.
Save Bondifrench/4f39c9a6d445e264db0020212163698b to your computer and use it in GitHub Desktop.
Mithril.js - Avoiding m.props
// m.prop is a great pattern, but Plain-old JavaScript Objects (POJO) are
// much more pleasant to work with.
// Here's an example of using POJOs with one- and two-way data binding.
// First, the helper methods
m.setValue = function (obj, prop) {
return m.withAttr('value', function(value) { obj[prop] = value })
}
// This helper isn't necessary if you're using ES6
m.set = function (obj, prop, value) {
return function () { obj[prop] = value }
}
//
// Usage Example #1
//
var CommentBox = {}
CommentBox.controller = function () {
var ctrl = this
ctrl.userInput = '' // No m.prop!
}
CommentBox.view = function (ctrl) {
return m('.comment-box', [
m('h1', "Please enter your comment:"),
m('textarea', { onchange: m.setValue(ctrl, 'userInput') }, ctrl.userInput)
])
}
//
// Usage Example #2
//
var TabbedContent = {}
TabbedContent.controller = function () {
var ctrl = this
ctrl.tab = 'first' // No m.prop!
}
TabbedContent.view = function (ctrl) {
return m('.tabs', [
m('.tab', { onclick: m.set(ctrl, 'tab', 'first') }, "First Tab"),
m('.tab', { onclick: m.set(ctrl, 'tab', 'second') }, "Second Tab"),
// ES6 version
// m('.tab', { onclick: () => ctrl.tab = 'first') }, "First Tab"),
// m('.tab', { onclick: () => ctrl.tab = 'second') }, "Second Tab"),
ctrl.tab === 'first' ? m('h1', "Content 1") : null,
ctrl.tab === 'second' ? m('h1', "Content 2") : null
])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment