访问DOM元素
你可以通过this.refs对象访问dom元素
而且还有大量的属性简写方式可以使用
比如:if="{...}",(有时候你需要对这些东西做一些特殊的处理才能用)
使用Jquery
如果你想在riot标签内部访问dom元素
你可能需要了解一下riot标签生命周期相关的知识
你会注意到,mount方法还没执行的时候,dom元素是不会被创建的
这就意味着,mount方法之前访问DOM元素,是不会成功的
请看如下代码:
<example-tag> <p id="findMe">Do I even Exist?</p> <script> var test1 = document.getElementById('findMe') console.log('test1', test1) // Fails this.on('update', function(){ var test2 = document.getElementById('findMe') console.log('test2', test2) // Succeeds, fires on every update }) this.on('mount', function(){ var test3 = document.getElementById('findMe') console.log('test3', test3) // Succeeds, fires once (per mount) }) </script> </example-tag>
也就是说,你只要在正确的函数中使用jquery是一点问题都没有的;
再看下面的代码(两种检索方式都是支持的,第一种就是jquery检索DOM)
<example-tag> <p id="findMe">Do I even Exist?</p> <p>Is this real life?</p> <p>Or just fantasy?</p> <script> this.on('mount', function(){ // Contexted jQuery $('p', this.root) // Contexted Query Selector this.root.querySelectorAll('p') }) </script> </example-tag>
mount输入参数
你可以在初始化的时候为riotjs标签传入更多参数,比如:
<script> riot.mount('todo', { title: 'My TODO app', items: [ ... ] }) </script>
你可以传递任何类型的数据;
可以是一个简单的object;
也可以是动态变化的数据存储(flux store)
在标签内部,你可以使用如下方法访问这些输入参数
<my-tag> <!-- Options in HTML --> <h3>{ opts.title }</h3> // Options in JavaScript var title = opts.title </my-tag>
riotjs标签的生命周期
riotjs标签按照如下步骤构造及渲染
- Tag构造
- Tag内部的js执行
- Tag内部的HTML中的表达式被执行
- Tag在浏览器上渲染,mount事件触发
一个riotjs标签在浏览器上渲染,mount事件触发后,何时会被更新呢?
- 当一个Tag内的事件被触发的时候(除非你设置了禁止更新变量e.preventUpdate为true)
- 当在Tag实例内部调用this.update()的时候
- 当在一个父组件实例内部调用this.update()的时候(该父组件下的所有子组件都会更新)
- 当调用riot.update()的时候(会触发全局更新)
当一个组件执行更新后,会触发update事件
监听生命周期事件
<todo> this.on('before-mount', function() { // before the tag is mounted }) this.on('mount', function() { // right after the tag is mounted on the page }) this.on('update', function() { // allows recalculation of context data before the update }) this.on('updated', function() { // right after the tag template is updated after an update call }) this.on('before-unmount', function() { // before the tag is removed }) this.on('unmount', function() { // when the tag is removed from the page }) // curious about all events ? this.on('*', function(eventName) { console.info(eventName) }) </todo>
你可以为一个事件设置多个监听
注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。