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.
Sample Code
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With