Mithril.js
A JavaScript front-end framework. A lightweight alternative to React or Vue.
Cheatsheet
import m from "mithril";
const PageView = {
view() {
return m(GreetingView, { name: "world" });
},
};
const GreetingView = {
view(vnode) {
const name = vnode.attrs.name;
return m("p", `Hello, ${name}!`);
},
};
// or, with classes:
class PageView {
view() {
return m(GreetingView, { name: "world" });
}
}
class GreetingView {
view(vnode) {
const name = vnode.attrs.name;
return m("p", `Hello, ${name}!`);
}
}
m.mount(document.body, PageView);
- To force a redraw:
m.redraw()
Component with state
interface MyViewAttrs {
x: string;
}
class MyView implements m.Component<MyViewAttrs> {
private x: string;
constructor(vnode: m.Vnode<MyViewAttrs>) {
this.x = vnode.attrs.x;
}
view(): m.Children {
return m("p", `My parameter: ${this.x}`);
}
}
// or, with constants
const MyView = {
oninit(vnode) {
vnode.state.x = 'whatever';
},
};
Event handlers
m("input", { onkeydown: (e) => this.onKeyDown(e) })
onKeyDown(e) {
if (e.key === "Enter") {
// ...
}
}
API requests
class MyView {
constructor() {
this.state = null;
}
oninit() {
m.request({ method: "GET", url: "/api/load" }).then(data => {
this.state = data;
});
}
myClickHandler() {
m.request({
method: "POST",
url: "/api/submit",
body: { ... },
headers: {
"Content-Type": "application/json",
},
});
}
}
Un-escape HTML output
m.trust("–")