8

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

Charles
  • 50,943
  • 13
  • 104
  • 142
Maslow
  • 18,464
  • 20
  • 106
  • 193
  • 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 Answers3

7

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.

LeoHorie
  • 1,320
  • 11
  • 11
4

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.

Alex
  • 11,479
  • 6
  • 28
  • 50
3

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) {})
}
JohnSz
  • 2,049
  • 18
  • 17