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.
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.
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.
Next, I'd like to work with the length option that's passed in, so I'm going to set it on this.
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.
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.
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.
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.
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.
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.