block by ramnathv d2f724794ca8c2ed468f

Mithril Patch for Simple Syntax

Mithril is an awesome library that makes it easy to build interactive UIs. It is similar to React in that it provides a virtual-dom.

Mithril supports components. But the default way to include a component within another involves calling m.component as opposed to just m which is the case for standard dom elements. This reduces the readability of the code. However, there is a simple patch that can be applied that overloads m based on whether the first argument is a string or a component.

Here is a simple example that outlines the idea.

## https://gist.github.com/impinball/5e4d6e64aba2ffb7cd23
## Patches Mithril to accept components as well as strings
@m = ((o) ->
  Object.assign (->
    (if typeof arguments[0] == 'string' then o else o.component).apply undefined, arguments
  ), o
)(m)

Hello = 
  view: (ctrl, props) ->
    m "h2", "Hello #{props.name}"

Input = 
  view: (ctrl, props) ->
    m "input[type='text']", {
      value: props.name()  
      oninput: m.withAttr("value", props.name)
    }

# App without Patch
App0 = 
  controller: ->
    vm:
      text: m.prop("")
  view: (ctrl, props) ->
    m "div", [
      m.component Input, {name: ctrl.vm.text}
      m.component Hello, {name: ctrl.vm.text()}
    ]

App = 
  controller: ->
    vm: 
      text: m.prop("")
  view: (ctrl, props) ->
    m "div", [
      m Input, {name: ctrl.vm.text}
      m Hello, {name: ctrl.vm.text()}
    ]

m.mount(
  document.body,
  m(App)
)