riot.js教程【三】访问DOM元素、使用jquery、mount输入参数、riotjs标签的生命周期

前文回顾
riot.js教程【二】组件撰写准则、预处理器、标签样式和装配方法;
riot.js教程【一】简介;html

访问DOM元素

你能够经过this.refs对象访问dom元素jquery

并且还有大量的属性简写方式能够使用浏览器

好比:if="{...}",(有时候你须要对这些东西作一些特殊的处理才能用)app

使用Jquery

若是你想在riot标签内部访问dom元素dom

你可能须要了解一下riot标签生命周期相关的知识函数

你会注意到,mount方法还没执行的时候,dom元素是不会被建立的this

这就意味着,mount方法以前访问DOM元素,是不会成功的code

请看以下代码:htm

<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标签按照以下步骤构造及渲染

  1. Tag构造
  2. Tag内部的js执行
  3. Tag内部的HTML中的表达式被执行
  4. Tag在浏览器上渲染,mount事件触发

一个riotjs标签在浏览器上渲染,mount事件触发后,什么时候会被更新呢?

  1. 当一个Tag内的事件被触发的时候(除非你设置了禁止更新变量e.preventUpdate为true)
  2. 当在Tag实例内部调用this.update()的时候
  3. 当在一个父组件实例内部调用this.update()的时候(该父组件下的全部子组件都会更新)
  4. 当调用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>

你能够为一个事件设置多个监听

相关文章
相关标签/搜索