Skip to content

Instantly share code, notes, and snippets.

@sloria
Last active April 8, 2018 02:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sloria/bbdf5e2fe3ae5bf96d99 to your computer and use it in GitHub Desktop.
Save sloria/bbdf5e2fe3ae5bf96d99 to your computer and use it in GitHub Desktop.
sugar for components in mithril
/**
* Provides sugar for creating a mithril component
* tweaked from @mindeavor's imlementation here: https://gist.github.com/mindeavor/25b8aa6810b244665a2e
*/
var defcomponent = function (component) {
return function(props, content) { return m.component(component, props, content); }
};
// DEFINING COMPONENTS
var Panel = defcomponent({
view: function(ctrl, props, children) {
return m('.panel.panel-default', [m('.panel-header', props.header)], children)
}
});
var EditPanel = defcomponent({
view: function(ctrl, props, children) {
// No need to call m.component!
return Panel({header: 'Edit'}, 'Content here');
}
});
// DEFAULT PROPS
// Using ES6 destructuring, we can provide default props
var Panel = defcomponent({
view(ctrl, {header='Default header'}={}, children) {
return m('.panel.panel-default', [m('.panel-header', header)], children)
}
});
// INITIAL STATE
// Similarly, we can define initial state
var Panel = defcomponent({
controller({enabled=true}={}) {
this.enabled = enabled;
}
view(ctrl, {header='Default header'}={}, children) {
return m('.panel.panel-default', {display: this.enabled ? 'block': 'none'},
[m('.panel-header', header)], children)
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment