Riot JS - DOM Events

Tim Kindberg
InstructorTim Kindberg
Share this video with your friends

Social Share Links

Send Tweet
Published 10 years ago
Updated 6 years ago

Riot can listen for raw dom events on any element by adding the on* attribute to elements and referencing an event handler. Let's walk through a couple examples.

[00:00] In the previous video, we auto-started our animation. Let's not auto-start the animation. Let's add some buttons that'll control the animation. There are life cycle events, which we just covered, but there are also raw DOM events, like onclick, onfocus, onchange.

[00:18] These events can be handled by adding an attribute to an element. On this button, I'll listen for the onclick event. All Riot event attributes need to evaluate to a function reference to work properly. The reference, just like all other bindings, is always in the context of the tag.

[00:37] I could write a new function down below, of this.click, but I don't need to include the "this" up here, in the binding. It's implied. What I want to do is actually trigger the start animation method on the trim tag. You can access any nested custom tag within the current tag by accessing this.tags.

[00:58] Again, you don't write out "this." Then you can reference them by name. Trim. I want to reference...Not call, just reference...the startAnimation method. We'll set up stopAnimation in the same way. Now we can start and stop the animation.

[01:21] Let's add an input so we can change the animation text. We'll bind its value to what, and on key up, we'll call the what change handler. We'll add a what change handler to this tag.

[01:47] It'll receive an event object that has been normalized to work consistently across all browsers. We can access the event's target, which will be the input, and get its value and update this.what with it. Now we can update the trim value on the fly.

[02:14] A nice little feature that Riot also has is that you can add a name attribute to any element to get a quick reference to that element. If I give this input a name of whatInput, then I can easily reference that element with self.whatInput as an alternative to e.target or in other scenarios.

[02:38] Remember that the attribute-based event handlers from this video only work with raw DOM events. I've included a list of those events at the bottom of the code example.

Gabriel Kohen
Gabriel Kohen
~ 10 years ago

Great intro Tim. I think the options lesson should be second in the playlist rather than third but I might have it wrong.

Prabu
Prabu
~ 9 years ago

Also, you can refer to a tag by name. For example, if you had multiple trim tags, you could refer a particular trim tag by assigning name="trim1" on the tag and then referrring it by self.tags.trim1

Markdown supported.
Become a member to join the discussionEnroll Today