Learn dynamic binding with Riot.js in 90 seconds

Vic Cekvenich
2 min readAug 1, 2018

--

The last years have brought a lot of JavaScript binding libraries, such as Vue.js, Mustache and Handlebars. Most developers know more than one JavaScript library. Riot.js is different because it is DOM-based and more declarative than others. This makes Riot.js easier to learn and use, and arguably easier to build and deploy.

Riot is easy to use with Pug. This helps with creating and maintaining clean Riot markup. We use a CLI to build Pug and Riot. Install it with:

npm -g i mbake

mbake is similar to Gulp or Grunt but written entirely in JavaScript.

Prerequisite: Learn how to build HTML from Pug

Create the file ‘index.pug’ in a ‘myProject’ folder, with Pug markup like this:

doctype html
html
head
body
p Hello World!

Also create a blank ‘dat.yaml’ file that mbake needs. Then run:

mbake ./myProject

This generates index.html with

<!DOCTYPE html>
<html>
<head/>
<body>
<p>Hello World!</p>
</body>
</html>

Your first Riot.js tag

Knowing Pug and mbake you can now learn data binding with Riot in less than 90 seconds. There are three steps: create the tag, build the tag, and use the tag in a page.

Step 1: Create the tag

Create first-tag.pug in the myProject folder:

first-tag
p Hi there.
p { num }
script.
doSomething(arg) {
this.update({num: arg+1})
}

This tag will update {num} with an incremented value when doSomething(value) is called. You would most likely do any fetch() of REST API data inside the tag.

Step 2: Build the tag

Run

mbake -t ./myProject

This generates first-tag.js, the compiled Riot tag.

Step 3: Use the tag in a page

Edit index.pug as follows:

head
script(src=’https://cdn.jsdelivr.net/npm/riot@3.10.3/riot.min.js')
script(src=’/first-tag.js’)
body
div
first-tag
script.
let firstTag = riot.mount(‘first-tag’)[0] // the first tag
firstTag.doSomething(41)

Then run

mbake ./myProject

This generates an index.html that uses the tag!

Review

You just learnt how to use Pug to build HTML and how to write and use a Riot tag that does data binding.

Read more about this approach at http://doc.metabake.org/mbake/.

PS: Check out an online class that covers Riot data binding more in-depth with a low code approach at http://class.metabake.org/home/.

--

--