How would I bind keypresses for an app?

javascript, mithril.js

Solution

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.

Problem

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

Original source