iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 6
0
Modern Web

AMP系列 第 6

AMP(Lession 6) - 使用 amp-bind 處理 view 、 data 、 user event 間的關係

使用 amp-bind 處理 view 、 data 、 user event 間的關係

相信不少人都有用過 MVPMVCMVVM, ... 各種架構,便於我們綁定 view 、 data 、 處理 user event;現在,在 AMP 的世界裡,請用 amp-bind 這個 component 來做這樣的處理

Required Script

<script async custom-element="amp-bind" src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>

基本的三部分

State

基本設定

槽狀使用 <amp-state><script type="application/json"> ,在裡面用 JSON 格式做一些設定。

修改 state 資料

在節點的 event 時,請使用 AMP.setState()AMP.pushState() , 並會對 state 做 deep-merge

例:

  • <button on="tap:AMP.setState({foo: 'bar', baz: myAmpState.someVariable})"></button>

  • <input type="range" on="change:AMP.setState({myRangeValue: event.value})">

  • <button on="tap:AMP.pushState({foo: '123'})">Set 'foo' to 123</button>

AMP.pushState() 同時還會修改頁面的 browser history stack

debug state

AMP.printState()

Expressions

使用類似 JavaScript 的表達式來對照這些 state 。

  • 只可操作 state ,並沒有權限影響 globals 的 window 或 document

  • 可使用的白名單 function

  • 通常並不允許使用客製的 function 、 class 、loops 。 Arrow functions 是可被允許做為 parameters 使畢的。例如: Array.prototype.map

  • 未定義的變數或不存在的array變數值(array-index-out-of-bounds),會回傳 null ,而非 undefined , 也不會 throw errors

完整的 Expressions 相關程式,請看 bind-expr-impl.jisonbind-expression.js

Bindings

使用在節點上的 property 來包住變數做綁定;例: [src]="myAnimals[currentAnimal].imageUrl"[class]="shirts[selected.sku].sizes['XS'] ? '' : 'unavailable'"

請注意,什麼節點或 compent 上能如何使用,是有官方規定的


下面為範例:

<!-- Store complex nested JSON data in <amp-state> elements. -->
<amp-state id="myAnimals">
  <script type="application/json">
    {
      "dog": {
        "imageUrl": "/img/dog.jpg",
        "style": "greenBackground"
      },
      "cat": {
        "imageUrl": "/img/cat.jpg",
        "style": "redBackground"
      }
    }
  </script>
</amp-state>

<p [text]="'This is a ' + currentAnimal + '.'">This is a dog.</p>

<!-- CSS classes can also be added or removed with [class]. -->
<p class="greenBackground" [class]="myAnimals[currentAnimal].style">
  Each animal has a different background color.
</p>

<!-- Or change an image's src with the [src] binding. -->
<amp-img width="300" height="200" src="/img/dog.jpg"
    [src]="myAnimals[currentAnimal].imageUrl">
</amp-img>

<button on="tap:AMP.setState({currentAnimal: 'cat'})">Set to Cat</button>

注意:<amp-bind> 並不會在頁面讀取時動作,它只會在 user 於頁面上執行動作時才會執行;這是為了確保無論頁面有無使用 <amp-bind> ,都能快速完成初始網頁。



上一篇
AMP(Lession 5) - 依區塊而改變文字大小 amp-fit-text
下一篇
AMP(Lession 7) - carousel 輪播圖片〈基礎篇〉
系列文
AMP30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言