riot.js教程【三】訪問DOM元素、使用jquery、mount輸入參數、riotjs標簽的生命周期


前文回顧
riot.js教程【二】組件撰寫准則、預處理器、標簽樣式和裝配方法;
riot.js教程【一】簡介;

訪問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標簽按照如下步驟構造及渲染

  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>

你可以為一個事件設置多個監聽


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM