Skip to content

Instantly share code, notes, and snippets.

@panych
Last active August 8, 2016 09:30
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 panych/f9722e1fe302f50ea913af5b489c74eb to your computer and use it in GitHub Desktop.
Save panych/f9722e1fe302f50ea913af5b489c74eb to your computer and use it in GitHub Desktop.
Mithril Wiki

Mithril personal wiki

Cleanup HTML attributes

Problem:

m('div', {foo: 'bar'}, 'hello');

// <div foo="bar">hello</div>

Solution:

var mainSection = {
  view: function(ctrl, attrs, children) {
    var sidebar = attrs.sidebar;
    var sectionAttrs = _.omit(attrs, 'sidebar');
    
    return m('section', sectionAttrs, [
      m('div.sidebar', {}, sidebar),
      m('div.main-content', {}, children)
    ])
  }
}

// usage
m(mainSection, {sidebar: m(sidebarComponent), className: 'app-section'}, [
  m('h1', 'Hello world')
])

Do not return null from view

Problem: null returned from view will rise an exception.

var Component = {};
Component.view = function(ctrl, opts) {
  return (opts.foo == 'bar') ? m('div', 'Bar') : null;
}

// Error will be rised
m.render(document.body, m(Component));

Solution: place conditions to render nothing (null) outside of the component or, if it's imposible, return an empty tag (m('span', null)).

var Component = {};
Component.view = function(ctrl, opts) {
  return m('div', 'Bar')
}

m.render(document.body, foo == 'bar' ? m(Component) : null);
// Convert node to mithril fragment (mNode)
var DOMFragment = function(markup) {
if (markup.indexOf("<!doctype") > -1) return [new DOMParser().parseFromString(markup, "text/html").childNodes[1]]
var container = document.createElement("div");
container.insertAdjacentHTML("beforeend", markup);
return container.childNodes;
}
var VirtualFragment = function recurse(domFragment) {
var virtualFragment = [];
for (var i = 0, el; el = domFragment[i]; i++) {
if (el.nodeType == 3) {
virtualFragment.push(el.nodeValue);
}
else if (el.nodeType == 1) {
var attrs = {};
for (var j = 0, attr; attr = el.attributes[j]; j++) {
attrs[attr.name] = attr.value;
}
var num = virtualFragment.length;
virtualFragment.push(
{
tag: el.nodeName.toLowerCase(),
attrs: attrs,
children: recurse(el.childNodes)
});
}
}
return virtualFragment;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment