Riot.js DOM Access
Jakob Jenkov |
Riot.js tags can use access DOM elements of the HTML inside the tag if the DOM elements have a
ref
attribute. Here is an example Riot.js tag definition which declares an <input>
element with ref
attribute, and a JavaScript that accesses that <input>
element:
<mytag> <h1>The Title</h1> <form> <input ref="abc" type="text" value="123"/> <input type="submit" value="Click" /> </form> <script> this.on("mount", function() { console.log("on mount"); console.log(this.refs.abc.value); }) </script> </mytag>
Notice the this.on("mount", ...)
function call in the JavaScript block. This function call adds
a "mount" event listener function which is fired when the tag is mounted in Riot.js.
Inside the function passed to the this.on("mount", ...)
function call
you can access the DOM elements with the ref
attributes. You do so via the this.refs
object. In the example above this is done via the statement this.refs.abc.value
. This statement
reads the value of the DOM element with the ref
attribute abc
.
The this.refs
object is not populated until the "mount" event has been fired. That is why
the example accesses it inside a "mount" event listener. This is important to keep in mind, as accessing
the this.refs
object at any time before the "mount" event has fired would leave you with
an empty this.refs
object - making access to the DOM elements impossible.
Tweet | |
Jakob Jenkov |