Phoenix Framework and Drab, Day 2: 100 Days of Code - to Elixir (Episode 5)

Drab is the extension library to Phoenix Framework for providing access to the browser's User Interface (DOM objects) from the server side. I try to make a simple 2 Numbers addition program to learn Elixir and Drab for the Phoenix framework. So today is the story about this.

Here is a simple 2 digit addition and subtraction example in Phoenix Drab. I simply take 2 fields and do basic math on that.
On the client side there is basic HTML with the input and the button:
 
  <h1>Result: <%= @text %></h1>

<form>
                <input name="text1">
                <input name="text2">
                 <button drab="click:add">Addition</button>
                <button drab="click:sub">Subtract</button>
</form>

The idea is to reuse the existing Phoenix templates, but make them living. drab="event:handler" attribute defines on which Phoenix function (handler) is going to be run in case of the given event. This handler is a function in the commander module, analogically to action in the controller. A commander is like a controller for living Drab pages.

defhandler add(socket, sender) do 
     {num1 , ""} = Integer.parse(sender.params["text1"])
     {num2, ""} = Integer.parse(sender.params["text2"]) 
     result = num1+num2 
     poke socket, text: Integer.to_string(result) 
end
defhandler sub(socket, sender) do 
                 {num1 , ""} = Integer.parse(sender.params["text1"]) 
                {num2, ""} = Integer.parse(sender.params["text2"]) 
                  result = num1-num2
                 poke socket, text: Integer.to_string(result)
 end

After processing the inputs, we need to present it to back in the browser. This is where we use poke/2 function - it pushes the assign (in this case: <%= @text %>) back to the browser. Input value is updated, without reloading the page.
Notice that you can have many event launchers (buttons, inputs, links) in the form, each one calling the different event handler. The second function handler is very similar, just makes the text lowercase.

You can find code at https://github.com/umair-iftikhar/phx_drab/tree/Day2_100DaysOfCode