Skip to content

Instantly share code, notes, and snippets.

@ramnathv
Last active December 7, 2015 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramnathv/d2f724794ca8c2ed468f to your computer and use it in GitHub Desktop.
Save ramnathv/d2f724794ca8c2ed468f to your computer and use it in GitHub Desktop.
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)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment