How to associate keystrokes for an application?

mithril talks a lot about binding and event if they are simple variables, but what about binding say key + to functionality? I tried binding m.withAttr('keyCode') to the controller method that I wanted to process, but nothing.

Code example

+6
source share
3 answers

Mithril does not have a helper for properties that are not attributes of a DOM element. withAttr only works with attributes of the DOM element (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 there to prevent redrawing if the key pressed is not the one you are looking for.

+6
source

Mithril does not process the entire page and events for you. You can addEventListener for window.onkeydown , and inside this callback do what you need, for example, refresh the controller or redraw the page.

http://jsbin.com/hikinoza/1/edit


m.prop or m.withAttr are not related by themselves. Actual binding occurs when you specify some onXXX property for an object, such as

 m('div', {onClick: myFunc}) 

This will attach the real onClick event to the real dom node div to be created.

+3
source

Mithril rendering fcn m(tag, attrs, children) allows you to specify the special config property in attrs . It allows you to call methods on a DOM element after it is created. See Section Accessing the Real DOM Element .

You can easily abuse Mithril, but use it properly to bind custom event handlers. Something like the following should work:

 m('li', {config: setupKeyHandler}, 'foo'); function setupKeyHandler (el, isInitialized, context) { el.addEventListener('keyup', function (event) {}) } 
+3
source

Source: https://habr.com/ru/post/969357/


All Articles