Build a Web Component with Riot.js and Yandex Maps
Riot.js is a lightweight user interface library that allows you to create self-contained and reusable web components using HTML, JavaScript and CSS. It is created by a Finnish company Muut and driven by real requirements for their quick and light commenting platform for websites.
Riot is deployed to unknown environments to support comment and forum widgets - it needs to be light and not interfere with other client libraries used on any given site. Learn more from the Riot.js Developer Guide.
Riot is described as React-like. I think it's a little bit easier to get into and thus serves as a better introduction to component based Front End web development. Coupled with RiotControl, a lightweight Flux Architecture Pattern implementation it can be used as a base for complex applications as well. These type of sandboxed UI components are ideal for JavaScript in Enterprise projects with hundreds of developers.
For testing Riot I decided to create a reusable Map component. At the time of the test Yandex released a new version of it's mapping API. This was a major release which rewritten code and much improved developer documentation.
Sensible people would've gone with a Facebook & Google powered map component, but I decided to give Riot.js & Yandex Maps a try.
Below is the end result. If you're the type of person to jump directly to the source, see the two file gist. Otherwise continue reading for a quick overview.
Bootstrap a Riot.js custom tag and Yandex Maps
In the HTML snippet above, I import three script files:
- My custom tag (js/tags/ymap.tag)
- Riot.js + Compiler (the tag will be compiled on the fly)
- Yandex Maps API (the map api)
In addition to the script files I need to mount the tag (on line 6), using the asterisk will mount all of your custom tags - more on this when I return with the RiotControl article on communicating between tags.
Once the tag is mounted we can start using it. The ymap tag comes with default values for zoom, coordinates, width and height. You can set them in the tag call as you do here.
Riot.js custom tag internals
The ymap custom tag handles all of the initialization, etc. required for an individual Yandex Map components. In Riot.js the markup it looks very similar to regular HTML, CSS and JavaScript.
In the markup we've got a root tag ymap which contains the whole component markup, logic and styling:
- On line 3 we create a div element for our container. In addition we append the id option
- On lines 6-9 we set default styles for the component. NOTE: Scoped is optional
- On lines 14-30 we set some defaults and override them if they're specified
- On lines 32-43 we call more initialization that can be done once the individual tag is mounted and ready for use - this includes the map initialization itself
- On lines 45-52 we initialize the map component with container, center point coordinates and zoom level