DEV Community

John Warner
John Warner

Posted on

Introduction to Modstache

In this post, I will introduce you to a JavaScript library called Modstache. I am the creator of this library and hope it is as useful to some of you as it has been for me. It is free to use.

What is Modstache?

Modstache is a reactive, JavaScript object to HTML DOM fragment mapper. What does this mean?

Many of you are familiar with using Mustache syntax to insert values from JavaScript variables and objects into HTML text using double curly braces to mark the areas to replace. Modstache goes a step further to use a special attribute "{}" to reactively replace element properties or attributes directly in the DOM fragment. Native HTML DOM fragments and Vanilla JavaScript are used, so no transpiler is necessary.

For example, given the following HTML:

<html>
<body>
  Your name is <span {}="name"></span>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

The following JavaScript code can be used to populate the name from a data model:

let data = { name: 'John' }
Modstache.fill(document.body, data); // You can also use _M_ instead of Modstache
Enter fullscreen mode Exit fullscreen mode

The fill method will find the {}="name" attribute in the span and update the text content of the span with the name from the data object. "textContent" is the default property to assign. This will result in the following:

<html>
<body>
  Your name is <span {}="name">John</span>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Installing Modstache

To use Modstache, you need to download or install the Modstache.js or Modstache.min.js file. Modstache can be downloaded from http://modstache.com or installed using npm with the command "npm install modstache"

Including Modstache

To include the Modstache library in your application, include a script tag with a source to the Modstache library:

<script src="modstache.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

That's it! The Modstache methods are accessed through the global Modstache or _M_ objects.

The most used method in Modstache is "fill". This method takes 2 (optionally 3) parameters. The DOM fragment, the data model object and an options object. This is documented at http://modstache.com/Documentation/Fill.

The Modstache fill method looks for the "{}" attributes in the DOM fragment and uses the value to direct the object/DOM mappings. The value is specified similar to a style attribute. The element property or attribute to map is specified first, followed by a colon ":", then the data object property. Different properties can be mapped by separating them with a semi-colon ";".

Here are some examples:

{}="style.color:color;value:myValue" // sets the text color and value property to the model color and myValue properties
{}="onchange:onchangeData" // sets the onchange event to event handler returned by the model onchangeData property
{}="display:item.show;onclick:{base}.myClick" // sets display to the "item" child object's show property. {base} is a special Modstache directive to refer to the data model. It is useful when arrays are used.
Enter fullscreen mode Exit fullscreen mode

Reactive Changes

Modstache is reactive, in that changes to the source data will automatically update the DOM:
For example, the following JavaScript execution after the previous example

data.name = 'Brent';
Enter fullscreen mode Exit fullscreen mode

will modify the DOM to

<html>
<body>
  Your name is <span {}="name">Brent</span>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

The modification is made without any additional calls to the Modstache library and does not require costly DOM comparisons.

Using Arrays to Duplicate Elements

Modstache uses arrays in the data to create multiple blocks of elements. For example:

  <table id='AgeTable'>
    <thead><tr><td>Name</td><td>Age</td></tr></thead>
    <tbody>
      <tr {}="rows">
        <td {}="name"></td><td {}="age"></td>
      </tr>
    </tbody>
  </table>
Enter fullscreen mode Exit fullscreen mode
let data = {
  rows: [
    { name: 'John', age: 35 },
    { name: 'Albert', age: 20 }
  ]
};

_M_.fill(document.getElementById('AgeTable'), data, { removeStache: true });
Enter fullscreen mode Exit fullscreen mode

The "removeStache" option removes the "{}" attribute from the element after processing. This will result in the following HTML:

  <table id='AgeTable'>
    <thead><tr><td>Name</td><td>Age</td></tr></thead>
    <tbody>
      <tr>
        <td>John</td><td>35</td>
      </tr>
      <tr>
        <td>Albert</td><td>20</td>
      </tr>
    </tbody>
  </table>
Enter fullscreen mode Exit fullscreen mode

After adding a new object to the array:

data.rows.push({ name: 'Mary', age: 28 });
Enter fullscreen mode Exit fullscreen mode

The table will automatically be updated to the following:

  <table id='AgeTable'>
    <thead><tr><td>Name</td><td>Age</td></tr></thead>
    <tbody>
      <tr>
        <td>John</td><td>35</td>
      </tr>
      <tr>
         <td>Albert</td><td>20</td>
      </tr>
      <tr>
        <td>Mary</td><td>28</td>
      </tr>
    </tbody>
  </table>
Enter fullscreen mode Exit fullscreen mode

Modstache supports calculations and events by using functions in the model as well:

let data = {
  color: 'red',
  alert: (ctx) => () => { alert('You clicked on the text.'); }
};
_M_.fill(document.getElementById('MessageAlert'), data);
Enter fullscreen mode Exit fullscreen mode
<div id="MessageAlert">
  <div {}="style.color:color;onclick:alert">This message is red!</div>
</div>
Enter fullscreen mode Exit fullscreen mode

This will set the color of the message to "red" and show an alert when clicked.

I have put together a short video to demonstrate installing and using Modstache you can watch below:

Top comments (0)