work-731198_1920

Mithril – Getting Started


Warning: Trying to access array offset on null in /home/re4mcom/domains/re4m.com/public_html/wp-content/plugins/codepen-embedded-pen-shortcode/codepen.php on line 16

Warning: Trying to access array offset on null in /home/re4mcom/domains/re4m.com/public_html/wp-content/plugins/codepen-embedded-pen-shortcode/codepen.php on line 17

Warning: Trying to access array offset on null in /home/re4mcom/domains/re4m.com/public_html/wp-content/plugins/codepen-embedded-pen-shortcode/codepen.php on line 16

Warning: Trying to access array offset on null in /home/re4mcom/domains/re4m.com/public_html/wp-content/plugins/codepen-embedded-pen-shortcode/codepen.php on line 17

Warning: Trying to access array offset on null in /home/re4mcom/domains/re4m.com/public_html/wp-content/plugins/codepen-embedded-pen-shortcode/codepen.php on line 16

Warning: Trying to access array offset on null in /home/re4mcom/domains/re4m.com/public_html/wp-content/plugins/codepen-embedded-pen-shortcode/codepen.php on line 17

Warning: Trying to access array offset on null in /home/re4mcom/domains/re4m.com/public_html/wp-content/plugins/codepen-embedded-pen-shortcode/codepen.php on line 16

Warning: Trying to access array offset on null in /home/re4mcom/domains/re4m.com/public_html/wp-content/plugins/codepen-embedded-pen-shortcode/codepen.php on line 17

Warning: Trying to access array offset on null in /home/re4mcom/domains/re4m.com/public_html/wp-content/plugins/codepen-embedded-pen-shortcode/codepen.php on line 16

Warning: Trying to access array offset on null in /home/re4mcom/domains/re4m.com/public_html/wp-content/plugins/codepen-embedded-pen-shortcode/codepen.php on line 17

This is the first blog of the technical series for the client-side JavaScript framework – Mithril

Nowadays, there are many JavaScript framework options which make developers’ lives easier, and the choice of which framework to work with on your next project can really be a tough one. Today, in terms of usage, Angular and React are the leading frameworks, with Vue.js constantly increasing its popularity. And then, there’s Mithril.

Mithril is a very compact and fast framework for building Single Page Applications and supports all modern browsers. According to the framework comparison chart on the official Mithril documentation website, we can see the following:

Framework Download size Update performance Documentation
Mithril v.2.0.0 8 kb 6.4 ms Well-written, easy to understand
Angular v2.0 135 kb 11.5 ms More complex than the others
React v 64 kb 12.1 ms Well-written, easy to understand
Vue v2.0 40 kb 9.8 ms Well-written, easy to understand

Table 1: Performances based on benchmark tests

According to the data presented in the table, we can see that Mithril has shown better performance in comparison to the other frameworks.

Installation

There are several ways to add/include Mithril.js in your project. The following are the quickest and easiest ways of including Mithril:

Directly in the JS file

By installing the package in your command line interface (CLI)

  • NPM – Using the command:
    $ npm install mithril --save 

    and including it by using  “require(‘mithril’);” or “import m from ‘mithril’

DOM elements

DOM(Document Object Model) is the way Javascript sees its containing pages’ data. It is an object that includes how the HTML/XHTML/XML is formatted. Examples for DOM elements include html, body, div etc. You can use CSS and add classes or id to DOM elements in order to style them and JavaScript to interact with them.

The m() function is one of the most important in Mithril.js. It is used to render any HTML components by calling it.

The m() function contains the following parameters:

  • selector – (required) This argument is of type String or Object. It is required and can be a CSS selector or component.
  • attributes – (optional) This argument is of type Object. It an optional argument and refers to HTML attributes or element properties
  • children – (optional) This argument is optional and can either be a renderable object (m calls or strings), or an array of them

The m() function return a vnode.

Example 1:

See the Pen Mithril – Example 1 by Monika Jandrevska (@monika-jandrevska) on CodePen.0

The m.render() function generates a virtual DOM tree and mounts it to the document.body. The document.body represents the <body> or <frameset> node of the current document. The “Hello World” string is example text that would be rendered.

Example 2:

See the Pen Mithril – Example 2 by Monika Jandrevska (@monika-jandrevska) on CodePen.0

This example shows how to express a paragraph with class paragraph1 and text “My frist paragraph in Mithril”.

The HTML output of the expression above is:

<p class=”paragraph1”>My first paragraph in Mithril</p>

Example 3:

See the Pen Mithril – Example 3 by Monika Jandrevska (@monika-jandrevska) on CodePen.0

This example shows how to handle multiple DOM elements. A div which acts like container, with class wrapper holds two child nodes – heading with class title and text “My first app in Mithril”, and button with text “Click here”.

Components

A Mithril component is basically an object with view() function. Using components in Mithril has several advantages:

  • Maintainability – Make change in only one file instead of making the same change in large number of files.
  • Reusability – Develop a component and use it whenever you need. Example for it is a Header component in a SPA.
  • Well-structured code – The usage of components decreases the complexity of the code. The code can be easily structured if there are several components instead of one big messy file
  • State data –  Data can be passed as an argument and used via this.vnode.data
  • Lifecycle callbacks –  Lifecycle callbacks are functions which called at various points during the lifetime of a component. (More about lifecycle methods in the next blog)

See the Pen Mithril – Components by Monika Jandrevska (@monika-jandrevska) on CodePen.0

In this example, Screen1 component is created using the view function. The return statement contains a div container with another div element in it and a button, when clicked, the alert function is called. The alert function simply prints text in the console. The m.mount() function, as the name implies, mounts the component to the virtual DOM. This component can be activated with the following line of code:

m.mount(document.body, Screen1);

The difference between m.mount() and m.render() is that m.mount() activates Mithril’s auto-redrawing system. According to the code above, the following HTML structure is created:

<div>

     <div class=”title”>Title</div>

     <button>Click me!</button>

</div> 

Routing

Since one-page applications are very rare, we should find a way to navigate through different pages of the application. This is where routing comes in. It literally means ‘jumping’ from one view to another. It is used to navigate users between different views of the application.

The following example takes a user from Screen 1 to Screen 2:

See the Pen Mithril – Routing by Monika Jandrevska (@monika-jandrevska) on CodePen.0

The #! Is called hashbang and is used to indicate that after the ‘/’, follows a route path.

If the application has several views, then m.route() is used:

m.route(root, "/screen1", {//default route
"/screen2": Screen2, //route for view called Screen2
"/screen2Details/:id": Screen3, //route for view called Screen2Details with id as parameter
"/screen4": Screen4, //route for view called Screen4
});

The route after the root component is a default one, and if something is wrong with the specific route or the component, then Mithril renders the default root.

XHR

XHR(XMLHttpRequest) is a method for communicating with the server. Mithril provides it’s own implementation (m.request) making XHR requests easy and attempts a redraw upon each XHR completion.

I will use REM as server for testing requests, which has also CORS enabled and can be accessed from anywhere. This server is used in the official documentation as well.

Here is an example of request for getting a list of users:

var users = []; // initializing an empty array called users
var listUsers = function(){
       m.request({ 
            method: “GET”,
            url: “http://rem-rest-api.herokuapp.com/api/users”,
            withCredentials: true,
        })
      .then(function(res){
           console.log(res);
      })
};

The m.request() function contains the following parameters:

  • Method – which type of action should be used, e.g other methods are PUT, DELETE, POST
  • Url – an url for the endpoint
  • Data – the actual data we are sending or receiving from the server (optional parameter)
  • withCredentials: whether to enable cookies or not

Conclusion

Mithril is very approachable, especially for beginners. It’s a tiny and elegant framework. It’s fast rendering structure is well-suited for different kinds of projects. Mithril.js is a fast and compact framework. The documentation on the official website is easy to read and implement.

This first blog covered the introduction to Mithril, the performance comparison to similar frameworks, as well as explanation and some simple examples for components, XHR and routing.

The next blog will be dedicated to Mithril key concepts – vnodes, the autoredraw system, keys, lifecycle methods and components. Stay tuned and read our blogs at: https://re4m.com/blog/.

References

Add a Comment

Your email address will not be published. Required fields are marked *