Search code examples
javascriptmithril.js

In mithril-js, how can vnode bind to click event


In Mithril.js (using webpack), I need to pass vnode to anonymous function:

how can it be done?

var Button = {
  view:function(vnode){
    return m('div',{onclick:(vnode)=> setSort(vnode)})
  }
}

function setSort(vnode){
  .... do somthing with vnode ....
}

Solution

  • Event handlers get passed the event object, not a vnode. You already have access to the vnode via closures, it's passed to your view method as the first argument.

    const Button = {
        view(vnode) {
            return m("button", {
                onclick() {
                    console.log(vnode);
                }
            }, "Button");
        }
    };
    
    m.mount(document.body, {
        view() {
            return m("div",
                m(Button)
            );
        }
    });
    

    Here's a running example on flems.io.