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>

你能夠爲一個事件設置多個監聽

相關文章
相關標籤/搜索