riot / riot

Simple and elegant component-based UI library
https://riot.js.org
Other
14.82k stars 967 forks source link

How to determine if tag is defined, by name? #1553

Closed rightwork closed 8 years ago

rightwork commented 8 years ago

I'd like to be able to throw an error to the user if a tag does not exist before trying to mount it, or at least in the process of mounting it.

I'm writing an app template, which uses the URL to determine which tag to mount. For example:

localhost:8080/page-home

will tell the app to mount the page-home tag. However, if the URL reads: (extra e on the end)

localhost:8080/page-homee

I'd then like to route the user to a 404 page telling them it doesn't exist. However, riot.mount() does not throw an error or return a different result, so the page just shows blank. I've found __tagImpl which seems to store all the tag names, but my JS experience is limited and I can't find a way to access it, although I know that's a hack if I do.

I could also workaround the issue by doing a DOM search for the element after it was supposed to be mounted. If the tag exists and has children/data underneath it then it's safe to assume the tag existed. Otherwise, it wasn't a valid tag and I could then redirect to an error page. But, a native riot way would be preferred if possible. I'm open to suggestions on how to better architect things the riot way, too.

Thanks to all the contributors for making riot such an awesome suite of simple tooling!

aMarCruz commented 8 years ago

@lp- :

var tags = riot.mount('page-home')
alert(JSON.stringify(tags))  // <-- array of mounted tags

See http://riotjs.com/api/#mounting

rightwork commented 8 years ago

Thank you @aMarCruz,

I did not mention I was using in-browser compilation, sorry. The solution was to wrap the riot.mount() in riot.compile() per the doc link you referenced. I remember reading that... it just wasn't clicking. I now get a return value from riot.mount()!