Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

    Riot JS - Tag Life Cycle Hooks

    Tim KindbergTim Kindberg

    Every tag in Riot has a lifecycle. I'll explore the three hooks: mount, update, and unmount while adding an animation feature for an existing tag. Lifecycle hooks are important for setting up, tearing down, and keeping a tag's view up to date after external logic is run.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    00:01 For events, WriteJS takes a similar approach to Angular or React. Let's completely change what the trim tag does, so I can show off some event concepts.

    00:09 I'll start by adding a script tag so I can get some nice WebStorm completion and highlighting. In here I'll store a reference to this and declare a couple of other variable that we'll use later.

    00:24 Next, I'd like to work with the length option that's passed in, so I'm going to set it on this.

    00:31 Now I'll paste in some animation code that I've already written. Every tag and write extends the write observable class, which allows the tag to listen to and broadcast events. It's super similar to jQuery. We can listen for an event with the tags "on" method.

    00:52 We can also use one, for a one-time handler, off, to remove a handler, and trigger to trigger a handler. Every tag also has three lifecycle events that are triggered automatically.

    01:07 A tag's lifecycle is, first, tag construction, then the JavaScript in the tag executes. Then HTML expressions are parsed, and then the update lifecycle event is triggered.

    01:26 Then the tag is mounted into the DOM, and the mount lifecycle event is triggered. If and when the tag is removed, by using the tags unmount method, the unmount event is triggered.

    01:40 In mount, I'd like to start the animation, and in unmount, I want to stop it, so it's not working. That's because we have to tell the trim tag to update its rendered view after each interval. This is really similar to Angular's scope apply method.

    02:07 Before we refresh, and have an infinite animation, let's add something in to stop it. We'll increase the count after each full animation. Then when we've looped 10 times, we'll call this tag built-in, unmount method. That will both remove from the DOM as well as trigger the unmount event which will in turn clear the animation interval.

    02:31 Now, when we refresh, you can see the lifecycle printed to the console. We see update one time, then the tag is mounted, and then we see update several times in a row before it's finally unmounted at the end.