Search code examples
javascriptjsxmithril.js

Build up some UI with mithril.js and jsx


I'm new to javascript and its ecosystem. I'm trying to build some components using mithril.js. My goal is to have a component that shows some properties and provides a couple of button for each of them. Just to learn about mithril.js and jsx. Here is what I did so far:

const m = require("mithril");
var Something = {
  _increase: function(category) {
    console.log("increase category: "+category);
  },
  _decrease: function(category) {
    console.log("decrease category: "+category);
  },
  view: function(vnode) {
    return <div> 
      {Object.keys(vnode.attrs.categories).map((category)=> {
        return <div>
          <label for={category}>{category}</label>
          <input type="number" id={category} value={vnode.attrs.categories[category]} />
          <button type="button" onclick="{this._increase(category)}">MORE</button>
          <button type="button" onclick="{this._decrease(category)}">LESS</button>
        </div>
      })}
    </div>
  }
}
export default Something;

Well, component seems to work fine, node doesn't complain and labels and buttons and fields are displayed on page, but, when I click on a button, nothing happen. It looks like event isn't fired. What's wrong?


Solution

  • Two things: (1) I think you should just put the function into the onclick handler braces instead of encoding the function in a string. (2) It looks like you're immediately invoking the function, not declaring that the onclick handler is a function that uses the category argument. Try passing in an anonymous function with no arguments, that way you when the onclick event is fired it can take in the category as a parameter:

    onclick={() => this._increase(category)}
    onclick={() => this._decrease(category)}