mithril talks plenty about binding and eventing if they are simple variable changes, but what about binding say the +
key to functionality? I tried m.withAttr('keyCode')
binding to the controller method that I wanted to handle it, but nothing.
-
You might try asking on the [Mithril mailing list](https://groups.google.com/forum/#!forum/mithriljs). – David May 16 '14 at 00:57
-
The first answer perfectly answers it. You can bind a `callback` to a key, basically. – Godje Jul 19 '17 at 05:26
3 Answers
Mithril doesn't have a helper for properties that aren't attributes of the DOM element. withAttr
only deals with DOM element attributes (as the name implies). For keyCode, you need to define a custom helper
function withKey(key, callback) {
return function(e) {
var ch = String.fromCharCode(e.keyCode)
if (ch == key) callback(key)
else m.redraw.strategy("none") //don't redraw (v0.1.20+ only)
}
}
m("div", {onkeypress: withKey("+", ctrl.doSomething)})
The else statement is just there to prevent a redraw if the pressed key is not the one you're looking for.

- 1,320
- 11
- 11
-
Wouldn't you have to set the redraw strategy again at some later time to turn auto-redrawing back on? (I'm really liking Mithril, BTW). – Lawrence Dol Sep 18 '14 at 23:02
-
1
-
Ahh. Good to know; I don't believe the documentation makes that clear anywhere - I don't recall reading that (though I may have missed it). – Lawrence Dol Sep 19 '14 at 02:56
-
Currently it's a bit skimpy, yes. Better docs will be released in 0.1.22 – LeoHorie Sep 19 '14 at 20:33
Mithril doesn't handle the entire page and it's events for you. You could addEventListener
for window.onkeydown
and within that callback do what you need, such as update the controller or redraw the page.
http://jsbin.com/hikinoza/1/edit
The m.prop
or m.withAttr
by themselves are not binding anything anywhere. The real binding happens when you specify some onXXX
property for an object such as
m('div', {onClick: myFunc})
This will attach a real onClick
event to the real div
dom node that will be created.

- 11,479
- 6
- 28
- 50
The Mithril rendering fcn m(tag, attrs, children)
allows you to specify the special property config
in attrs
. It allows you to call methods on the DOM element after it gets created. See the section called Accessing the real DOM element.
You can easily abuse Mithril with this, but its a proper use for attaching non-standard event handlers. Something like the following should work:
m('li', {config: setupKeyHandler}, 'foo');
function setupKeyHandler (el, isInitialized, context) {
el.addEventListener('keyup', function (event) {})
}

- 2,049
- 18
- 17