DEV Community

Cover image for Create calculator using mithril
Manish Champaneri
Manish Champaneri

Posted on • Originally published at learnit.mchampaneri.in

Create calculator using mithril

What you are building is this : https://xp4xo.csb.app/

Table of content
# Setup basic scaffold for calculator appliaction{#setup-basic-scaffold-for-calculator-application}

Make HTML page having basic html tags and having mithril cdn within it. Also make sure to add a mounting point to the page which we will be using to inject our calculator code afterwards.

<html>
  <head> 
    <title> Calculator using mithril </title>
    <script src="https://unpkg.com/mithril/mithril.js">
    </script>
  </head>
  <body>
     <!-- Mounting point of calculator -->
     <div id='app'>
  </body>
</html>
# Mount mithril to the mounting point using m.mount {#mount-mithril-to-the-mounting-point-using-m-mount}

We will be using m.mount function here to render our application.

In hello world example we have used m.render function which is internally used by m.mount function. You can find comparision between m.mount vs m.render here.

Signature of m.mount function

m.mount( mountingPoint , mithrilComponent )
Parameter Value
mountingPoint Dom element where you want to mount mithril appliaction
mithrilComponent Mithril component you want to mount to the dom

Mount mithril to div with id 'app' using m.mount

Mithril component is actully an object. An object which have mithril life-cycle methods and view method have defined in it.

var mountingPoint = document.getElementById('app')
m.mount ( mountigPoint, { 
  view() { 
    return m('Hello') 
  }
)

Let's assing mithril component to a variable and then pass it as paramter to make this code more readable.

var mithrilComponent =  { 
  view() { 
    return m('Hello') 
  }
}
var mountingPoint = document.getElementById('app')
m.mount ( mountigPoint ,  mithrilComponent )
# Preapare UI for our calculator{#prepare-ui-for-our-calculator}

We have prepared mounting point and rended a component for verification. Now let's create basic UI for our preety simple calculator.

var calculatorComp = {
    view() {
      return m("div", [
        m("table", [
          m("tr", [
             m("td",{
                  colspan: 4,
                  style: "width:100%;text-align:right; border:1px solid #ccc"
                },
                m("lable", { style: "width:100%,text-align:right" }, "0")
               )
            ]),
            m("tr", [
              m("td", m("button", "1")),
              m("td", m("button", "2")),
              m("td", m("button", "3")),
              m("td", m("button", "+"))
            ]),
            m("tr", [
              m("td", m("button", "4")),
              m("td", m("button", "5")),
              m("td", m("button", "6")),
              m("td", m("button", "-"))
            ]),
            m("tr", [
              m("td", m("button", "7")),
              m("td", m("button", "8")),
              m("td", m("button", "9")),
              m("td", m("button", "*"))
            ]),
            m("tr", [
             m("td", { rowspan: 2 }, m("button", "0")),
             m("td", m("button", "=")),
             m("td", m("button", "/"))
           ])
         ])
       ]);
    }
 };
# Create logic for arhitmatic operators & input{#create-logic-for-arithmatic-operators-and-inputs}

Now we need to define logic to process input according to operators. We will be using component's objects property to store our data.

var calculatorComp = {
  previousInput: "0",
  currentInput: "0",
  currentResult: "0",
  previousOperator: "+",
  . . .

We will define to functions one to handle on click events of digit buttons and one for click event of operators

numberButtonClick(digit) {
  if (
    this.currentInput == 0 ||
    this.currentInput == this.currentResult
  ){
      this.currentInput = digit.toString();
    } else {
      this.currentInput = this.currentInput + digit.toString();
   }
},

operatorButtonClick(operator) {
  if (this.currentResult != this.currentInput) {
   this.previousInput = this.currentInput;
  } else {
    this.previousInput = 0;
  }

  switch (this.previousOperator) {
     case "+": {
     this.currentResult =
     parseInt(this.currentResult) + parseInt(this.previousInput);
     break;
   }
   case "-": {
      this.currentResult =
      parseInt(this.currentResult) - parseInt(this.previousInput);
      break;
   }
   case "*": {
      this.currentResult =
      parseInt(this.currentResult) * parseInt(this.previousInput);
      break;
   }
   case "/": {
      this.currentResult =
      parseInt(this.currentResult) / parseInt(this.previousInput);
      break;
  }
  default: {
      console.log(this.currentResult);
  }
 }
 this.currentInput = this.currentResult;
 this.previousOperator = operator;
},

Now only thing is left is to assign this methods to buttons we have created

// Assigning digit button click event
m("td",
   m("button",
       { onclick: e => {
           e.preventDefault();
           this.numberButtonClick(1);
            m.redraw();
       }
     },"1"
   )
),

// Assigning operatorbutton click event
m("td",
   m("button",
       { onclick: e => {
           e.preventDefault();
           this.operatorButtonClick("+");
            m.redraw();
       }
     },"1"
   )
),

It would be too long if I write whole code here ;) , so instead see whole code from example hosted on codesandbox shown in next section.

# Live example hosted on codesandbox{#live-example-hosted-on-codesandbox}

https://codesandbox.io/embed/hello-world-example-xp4xo

Discussion (0)