Search code examples
javascriptmithril.js

Mithriljs add onkeydown event when component is created


I am trying to initialize an onkeydown event when a component is created:

var KeyboardComponent = {
     parse: function(e){
       console.log("pressed: " + e.key);
     },
     view: function() {
        return m("div.keyboard-container", {onkeydown: (e) => this.parse(e)});
     }
};

m.mount(document.body, KeyboardComponent);

But when I type anything, no event is printed in the console. I'm not sure how the event be defined, thank you !


Solution

  • Try adding m('input') inside the div and typing in the input box. It works for me.

    var KeyboardComponent = {
         parse: function(e){
           console.log("pressed: " + e.key);
         },
         view: function() {
            return m("div.keyboard-container", {
                onkeydown: (e) => this.parse(e)
            }, m('input'));
         }
    };
    
    m.mount(document.body, KeyboardComponent);