Tech and Media Labs
This site uses cookies to improve the user experience.




Riot.js Events

Jakob Jenkov
Last update: 2017-04-21

Riot.js tags can listen for both Riot.js and DOM events. This Riot.js event tutorial will show you how.

According to the Riot.js docs you can attach event listeners using Riot.js expressions. However, I am having a hard time getting these event listeners to work properly. Therefore I will stick to showing you how to add event listeners with JavaScript. These event listeners works just as fine and I find them easier to understand and reason about.

Here is a Riot.js tag definition which attaches a Riot.JS "mount" event listener, and inside this event listener attaches two DOM event listeners:

<mytag>
<h1>The Title</h1>

<form ref="theform">
    <button ref="thebutton">Click</button>
    <input type="submit" value="Submit" />
</form>


<script>

this.on("mount", function() {
    this.refs.thebutton.onclick = function(e) {
        console.log("Button clicked");
        return false;
    };

    this.refs.theform.onsubmit = function(e) {
        console.log("Form submitted");
        return false;
    };
});
</script>

</mytag>    

The example attaches a DOM event listener for the <form> element and the <button> element. Notice how the DOM elements are referenced via the this.refs object as explained in Riot.JS DOM Access .

Notice also how the two DOM event listeners return false. This to avoid the default behaviour of submitting the form when the <button> or <input type="submit"> is clicked.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC