Introduction to Modstache
Tags: javascript, library, html, reactive
Published: 2021-06-03 22:45:58

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
<html>
<body>
  Your name is <span {}="name"></span>
</body>
</html>
```
The following JavaScript code can be used to populate the name from a data model:

```Javascript
let data = { name: 'John' }
Modstache.fill(document.body, data); // You can also use _M_ instead of Modstache
```
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
<html>
<body>
  Your name is <span {}="name">John</span>
</body>
</html>
```
#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:
```javascript
<script src="modstache.min.js"></script>
```
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:
```javascript
{}="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.
```

# 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
```JavaScript
data.name = 'Brent';
```
will modify the DOM to
```html
<html>
<body>
  Your name is <span {}="name">Brent</span>
</body>
</html>
```
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:
```html
  <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>
```
```javascript
let data = {
  rows: [
    { name: 'John', age: 35 },
    { name: 'Albert', age: 20 }
  ]
};

_M_.fill(document.getElementById('AgeTable'), data, { removeStache: true });
```
The "removeStache" option removes the "{}" attribute from the element after processing. This will result in the following HTML:
```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>
```
After adding a new object to the array:
```javascript
data.rows.push({ name: 'Mary', age: 28 });
```
The table will automatically be updated to 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>
      <tr>
        <td>Mary</td><td>28</td>
      </tr>
    </tbody>
  </table>
```
Modstache supports calculations and events by using functions in the model as well:
```javascript
let data = {
  color: 'red',
  alert: (ctx) => () => { alert('You clicked on the text.'); }
};
_M_.fill(document.getElementById('MessageAlert'), data);
```
```html
<div id="MessageAlert">
  <div {}="style.color:color;onclick:alert">This message is red!</div>
</div>
```
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:
{% youtube T5bG6IXUfaw %}