Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I bind keypresses for an app?

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

like image 427
Maslow Avatar asked May 15 '14 20:05

Maslow


2 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.

like image 50
LeoHorie Avatar answered Sep 20 '22 14:09

LeoHorie


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.

like image 39
Alex Avatar answered Sep 17 '22 14:09

Alex