Riot JS - Tag Options

Tim Kindberg
InstructorTim Kindberg

Share this video with your friends

Send Tweet
Published 7 years ago
Updated 3 years ago

Tag Options allow you to abstract your custom tag elements into reusable objects by allowing the tag-user to specify the dynamic parameters of their component.

[00:00] What if I wanted the greeting part of my "Hello World" tag to be customizable? If I wanted to be able to do like Angular does, and pass in some parameters? Let's replace "Hello" with a data-bound property of ops.greeting. Custom elements can accept parameters called Options.

[00:20] This ops object is special in Riot. It will contain all the options passed into a tag. There are two ways to pass in options. If you're working in an uncompiled file, like the body of the index file, then you pass parameters in via the Mount Call.

[00:37] Pass an object as the second parameter whose keys and values are option names and values. You can send along extra data if you'd like, but if you don't use it in your tag, it's ignored. We'll refresh and see if our options are working properly...Greeting worked and punctuation was ignored.

[01:00] To demonstrate the second way, I have to make another tag. Let's make a trim tag. I just want a simple way to trim a string value. With data binding, I'll pass in a value that I want to trim...and I'll pass in a length for the trim.

[01:23] Everything in the curly brackets is regular JavaScript. You can go crazy in there, but really you should keep it simple. Here's a "Gotcha." It's important to use a nested HTML element like span because otherwise, Riot things are just trying to write some badly formatted JavaScript.

[01:42] The second way to pass in options. If you're working in a complied file like this .tag file, then you use custom tags without any call to riot.mount. The tags are mounted automatically.

[01:55] You pass in options as attributes. We'll set our value option and our length to three. We'll refresh and see if our trim tag options are working.

[02:08] Of course, you can also pass data-bound properties to your custom tag options and they'll work just as expected. Now, it's trimming the local this.what value.