Google AMP - Data Binding

Amp-bind ajuda a adicionar interatividade aos componentes amp e tags html com base em uma ação usando data-binding e expressões semelhantes a JS. Este capítulo discute a vinculação de dados em detalhes.

Para trabalhar com amp-bind, precisamos adicionar o seguinte script à nossa página -

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

Vamos entender isso totalmente com a ajuda de um exemplo prático, conforme mostrado -

Exemplo

<!doctype html>
<html amp lang = "en">
   <head>
      <meta charset = "utf-8">
      <script async src = "https://cdn.ampproject.org/v0.js"></script>
      <title>Google AMP - Amp Bind</title>
      <link rel = "canonical" href = 
         "http://example.ampproject.org/article-metadata.html">
      <meta name = "viewport" content = "width = device-width,
         minimum-scale = 1,initial-scale = 1">
      <style amp-boilerplate>
         body{
            -webkit-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;animation:
            -amp-start 8s steps(1,end) 0s 1 normal both
         }
         @-webkit-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}
      </style>
      <noscript>
         <style amp-boilerplate> 
            body{
               -webkit-animation:none;
               -moz-animation:none;
               -ms-animation:none;
               animation:none
            }
         </style>
      </noscript>
      <script async custom-element = "amp-bind" 
         src = "https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>
      <style amp-custom>
         button{ 
            background-color: #ACAD5C; 
            color: white; 
            padding: 12px 20px; 
            border: none; 
            border-radius: 4px; 
         }
      </style>
   </head>
   <body>
      <h3>Google AMP - Amp Bind</h3>
      <p [text] = "'Hello ' + world + '.'">
         Click on the button to change the text
      </p>
      <button on = "tap:AMP.setState({world: 'This is amp-bind example'})">
      Click Here
      </button>
   </body>
</html>

Resultado

Clique no botão para ver a alteração do texto conforme mostrado abaixo -

Assim, no exemplo mostrado acima, usamos amp-bind para alterar o texto ao clicar no botão.

Amp-bind tem três componentes -

  • State- Inicialmente, o estado está vazio. Depois de clicar no botão, o estado é alterado. Por exemplo,

<button on = "tap:AMP.setState({world: 'This is amp-bind example'})">
   Click Here
</button>

O método AMP.setState é usado para alterar o estado. A variávelworld é atribuído o valor This is amp-bind example. A variávelworld é usado dentro da tag html -

<p [text] = "'Hello ' + world + '.'">
   Click on the button to change the text
</p>

Ao clicar no botão, world recebe um novo valor: Este é um exemplo de amp-bind.

Também podemos usar amp-state com ligação, conforme mostrado abaixo -

<amp-state id = "myState">
   <script type = "application/json">
      {
         "foo": "bar"
      }
   </script>
</amp-state>

A expressão será atribuída bmyState.foo durante a ligação.

  • Expressions - As expressões para amp-bind funcionar são fornecidas da seguinte maneira -

'Hello ' + world

world é dito ser um state variable.

  • Bindings- As ligações são aplicadas a atributos especiais no formulário [atributos]. Por exemplo -

<p [text] = "'Hello ' + world + '.'">
   Click on the button to change the text
</p>

No exemplo acima, [text] tem a expressão que é usada para ligar o p tag.

Podemos usar o seguinte atributo para ligações -

  • [text]
  • [class]
  • [hidden]
  • [width]
  • [height]

Ligações também podem ser feitas em componentes de amplificador e apenas atributos específicos são permitidos. A lista a seguir mostra os componentes e atributos suh -

Sr. Não Componente Amp Atributos e descrição
1 <amp-carousel type = slides> [slide]*

Mude o slide usando este comportamento de ligação

2 <amp-date-picker> [min]

min -> Define a data selecionável mais antiga

[max]

max -> Define a última data selecionável

3 <amp-iframe> [src]

Alterar src de iframe

4 <amp-img> [alt] [attribution] [src] [srcset]

Podemos alterar alt, atribuição, src e srcset. Se src for alterado, altere srcset à medida que é usado para armazenamento em cache

5 <amp-lightbox> [open]*

Você pode mostrar / ocultar a caixa de luz vinculando para abrir

6 <amp-list> [src]

Se a expressão for uma string, busca e renderiza JSON do URL da string. Se a expressão for um objeto ou matriz, renderiza os dados da expressão.

7 <amp-selector> [selected]* [disabled]

Altera o (s) elemento (s) filho (s) selecionado (s) atualmente, identificados por seus valores de atributo de opção. Suporta uma lista de valores separados por vírgulas para seleção múltipla

Ligação usando Amp-State

Podemos definir amp-state com todos os dados que gostaríamos de usar no elemento html ou componente amp.

Os dados usados ​​dentro do amp-state devem estar no formato json conforme mostrado abaixo -

<amp-state id = "myCarsList">
   <script type = "application/json">
      {
         "currentcar" : "bmw",
         "audi": {
            "imageUrl": "images/audi.jpg"
         },
         "bmw": {
            "imageUrl": "images/bmw.jpg"
         }
      }
   </script>
</amp-state>

Assim, definimos pares de valores-chave com o nome do carro e a imagem usada para o carro.

Amp-bind em texto e Amp-Image

Um exemplo de trabalho usando amp-state com amp-bind é mostrado abaixo -

<!doctype html>
<html amp lang = "en">
   <head>
      <meta charset = "utf-8">
      <script async src = "https://cdn.ampproject.org/v0.js"></script>
      <title>Google AMP - Amp Bind</title>
      <link rel = "canonical" href =
         "http://example.ampproject.org/article-metadata.html">
      <meta name = "viewport" content = "width = device-width,
         minimum-scale = 1,initial-scale = 1">
      <style amp-boilerplate>
         body{
            -webkit-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;animation:
            -amp-start 8s steps(1,end) 0s 1 normal both
         }
         @-webkit-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}
         }
      </style>
      <noscript>
         <style amp-boilerplate> 
            body{
               -webkit-animation:none;
               -moz-animation:none;
               -ms-animation:none;
               animation:none
            }
         </style>
      </noscript>
      <script async custom-element = "amp-bind" src =
         "https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>
      <style amp-custom>
         button{ 
            background-color: #ACAD5C; 
            color: white; 
            padding: 12px 20px; 
            border: none; 
            border-radius: 4px; 
            cursor: pointer; 
            float: left;
         }
      </style>
   </head>
   <body>
      <h3>Google AMP - Amp Bind</h3>
      <amp-state id = "myCarsList">
         <script type = "application/json">
            {
               "currentcar" : "bmw",
               "audi": {
               "imageUrl": "images/audi.jpg",
               "style": "greenBackground"
               },
               "bmw": {
               "imageUrl": "images/bmw.jpg",
               "style": "redBackground"
               }
            }
         </script>
      </amp-state>
      <amp-img 
         width = "300" 
         height = "200" 
         src = "images/bmw.jpg" 
         [src] = "myCarsList[currentcar].imageUrl">
      </amp-img>
      <p [text] = "'This is a ' + currentcar + '.'">
         This is a BMW.
      </p>
      <br/>
      <button on = "tap:AMP.setState({currentcar: 'audi'})">
         Change Car
      </button>
   </body>
</html>

Resultado

Clique no botão para ver a imagem da mudança do carro e também o texto abaixo.

Amp-bind em vídeo e IFrame

Agora veremos um exemplo de trabalho que mudará o amp-iframe e amp-video src.

<!doctype html>
<html amp lang = "en">
   <head>
      <meta charset = "utf-8">
      <script async src = "https://cdn.ampproject.org/v0.js"></script>
      <title>Google AMP - Amp Bind</title>
      <link rel = "canonical" href =
         "http://example.ampproject.org/article-metadata.html">
      <meta name = "viewport" content = "width = device-width,
         minimum-scale = 1,initial-scale = 1">
      <style amp-boilerplate>
         body{
            -webkit-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;animation:
            -amp-start 8s steps(1,end) 0s 1 normal both
         }
         @-webkit-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}
      </style>
      <noscript>
         <style amp-boilerplate> 
            body{
               -webkit-animation:none;
               -moz-animation:none;
               -ms-animation:none;
               animation:none
            }
         </style>
      </noscript>
      <script async custom-element = "amp-bind" src =
         "https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>
      <script async custom-element = "amp-video" src =
         "https://cdn.ampproject.org/v0/amp-video-0.1.js"></script>
      <script async custom-element = "amp-iframe" src =
         "https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>
      <style amp-custom>
         button{ 
            background-color: #ACAD5C; 
            color: white; 
            padding: 12px 20px; 
            border: none; 
            border-radius: 4px; 
            cursor: pointer; 
            float: left;
         }
      </style>
   </head>
   <body>
      <h3>Google AMP - Amp Bind</h3>
      <button on = "tap:AMP.setState({currentlist: 'list1'})">
      Click Here
      </button>
      <br/>
      <br/>
      <amp-state id = "myList">
         <script type = "application/json">
            {
               "currentlist" : "",
               "list1": {
                  "url": "video/m.mp4",
                  "style": "greenBackground",
                  "iframeurl":"https://maps.google.com/maps?q=hyderabad&t=&z=13&ie=UTF8&iwloc=&output=embed"
               }
            }
         </script>
      </amp-state>
      <h3>AMP - IFRAME</h3>
      <amp-iframe 
         width = "600"
         title = "Google map"
         height = "400"
         layout = "responsive"
         sandbox = "allow-scripts allow-same-origin allow-popups"
         frameborder = "0"
         src = "https://maps.google.com/maps?q=telangana&t=&z=13&ie=UTF8&iwloc=&output=embed"
         [src] = "myList[currentlist].iframeurl">
         <amp-img 
            layout = "fill" 
            src = "images/loading.jpg" 
            placeholder
            >
         /amp-img>
      </amp-iframe>
      <h3>AMP - VIDEO</h3>
      <amp-video 
         id = "amp-video" 
         src = "video/samplevideo.mp4" 
         layout="responsive" 
         [src] = "myList[currentlist].url" 
         width = "300" 
         height = "170" autoplay controls>
      </amp-video>
   </body>
</html>

Observe que aqui usamos amp-state com iframesrc e video src.

<amp-state id = "myList">
   <script type = "application/json">
      {
         "currentlist" : "",
         "list1": {
            "url": "video/m.mp4",
            "style": "greenBackground",
            "iframeurl":"
            https://maps.google.com/maps?q=hyderabad&t=&z=13&ie=UTF8&iwloc=&output=embed"
         }
      }
   </script>
</amp-state>

A currentlist é definida como vazia e, ao tocar no botão, é definida como list1. A currentlist varaible é usada para src de iframe e vídeo, conforme mostrado abaixo -

<amp-iframe width="600"
   title = "Google map"
   height = "400"
   layout = "responsive"
   sandbox = "allow-scripts allow-same-origin allow-popups"
   frameborder = "0" src = "https://maps.google.com/maps?q=telangana&t=&z=13&ie=UTF8&iwloc=&output=embed"
   [src] = "myList[currentlist].iframeurl">
      <amp-img layout = "fill" src = "images/loading.jpg" placeholder>
      </amp-img>
</amp-iframe>
<amp-video id = "amp-video" src = "video/samplevideo.mp4" 
   layout = "responsive" [src] = "myList[currentlist].url" width = "300" 
   height = "170" autoplay controls>
</amp-video>

Resultado

Clique no botão para ver o vídeo e a alteração do iframe src.

Amp-bind com amp-lightbox

Agora, vamos ver o funcionamento da ligação e do amp-lightbox quando usados ​​juntos.

Exemplo

<!doctype html>
<html amp lang = "en">
   <head>
      <meta charset = "utf-8">
      <script async src="https://cdn.ampproject.org/v0.js"></script>
      <title>Google AMP - Amp Bind</title>
      <link rel = "canonical" href =
         "http://example.ampproject.org/article-metadata.html">
      <meta name = "viewport" content = "width = device-width,
         minimum-scale = 1,initial-scale = 1">
      <style amp-boilerplate>
         body{
            -webkit-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;animation:
            -amp-start 8s steps(1,end) 0s 1 normal both
         }
         @-webkit-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}
      </style>
      <noscript>
         <style amp-boilerplate> 
            body{
               -webkit-animation:none;
               -moz-animation:none;
               -ms-animation:none;
               animation:none
            }
         </style>
      </noscript>
      <script async custom-element = "amp-bind" src =
         "https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>
      <script async custom-element = "amp-lightbox" src =
         "https://cdn.ampproject.org/v0/amp-lightbox-0.1.js"></script>
      <style amp-custom>
         button{ 
            background-color: #ACAD5C; 
            color: white; 
            padding: 12px 20px; 
            border: none; 
            border-radius: 4px; 
            cursor: pointer; 
            float: left;
         }
         .lightbox {
            background: rgba(211,211,211,0.8);
            width: 100%;
            height: 100%;
            position: absolute;
            display: flex;
            align-items: center;
            justify-content: center;
         }
      </style>
   </head>
   <body>
      <h3>Google AMP - Amp Bind</h3>
      <button on = "tap:AMP.setState({displaylightbox: true})">
      Click Here
      </button>
      <br/>
      <br/>
      <h3>AMP - Lightbox</h3>
      <amp-lightbox 
         id = "my-lightbox" 
         [open] = "displaylightbox" 
         layout = "nodisplay" 
         close-button>
         <div class = "lightbox" on = "tap:AMP.setState({displaylightbox: false})">
            <amp-img alt = "Beautiful Flower"
               src = "images/loreal.gif"
               width = "246"
               height = "205">
            </amp-img>
         </div>
      </amp-lightbox>
   </body>
</html>

Para usar a vinculação no amp-lightbox, usamos [open] no amp-lightbox como mostrado abaixo -

<amp-lightbox id = "my-lightbox" [open] = "displaylightbox" 
   layout = "nodisplay" close-button>
   <div class = "lightbox" on="tap:AMP.setState({displaylightbox: false})">
      <amp-img alt = "Beautiful Flower"
         src = "images/loreal.gif"
         width = "246"
         height = "205">
      </amp-img>
   </div>
</amp-lightbox>

O [open] = “displaylightbox” é um estado variável que é alterado com o clique do botão e com o toque da div lightbox para true / false -

<button on = "tap:AMP.setState({displaylightbox: true})">
   Click Here
</button>

<div class = "lightbox" on = "tap:AMP.setState({displaylightbox: false})">
   <amp-img alt = "Beautiful Flower"
      src = "images/loreal.gif"
      width = "246"
      height = "205">
   </amp-img>
</div>

Resultado

Ligação do amplificador ao elemento de entrada

Vamos entender o funcionamento da ligação de amp para o elemento de entrada com a ajuda de um exemplo de trabalho como mostrado -

<!doctype html>
<html amp lang = "en">
   <head>
      <meta charset = "utf-8">
      <script async src = "https://cdn.ampproject.org/v0.js"></script>
      <title>Google AMP - Amp Bind</title>
      <link rel = "canonical" href=
         "http://example.ampproject.org/article-metadata.html">
      <meta name = "viewport" content = "width = device-width,
         minimum-scale = 1,initial-scale = 1">
      <style amp-boilerplate>
         body{
            -webkit-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;animation:
            -amp-start 8s steps(1,end) 0s 1 normal both
         }
         @-webkit-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes 
         -amp-start{from{visibility:hidden}to{visibility:visible}}
      </style>
      <noscript>
      <style amp-boilerplate> 
         body{
            -webkit-animation:none;
            -moz-animation:none;
            -ms-animation:none;
            animation:none
         }
      </style>
      <noscript>
      <script async custom-element = "amp-bind" 
         src = "https://cdn.ampproject.org/v0/amp-bind-0.1.js">
         <script>
         <script async custom-element = "amp-lightbox" 
            src = "https://cdn.ampproject.org/v0/amp-lightbox-0.1.js">
      </script>
      <style amp-custom>
         button{ 
            background-color: #ACAD5C; 
            color: white; 
            padding: 12px 20px; 
            border: none; 
            border-radius: 4px; 
            cursor: pointer; 
            float: left;
         }
         .lightbox {
            background: rgba(211,211,211,0.8);
            width: 100%;
            height: 100%;
            position: absolute;
            display: flex;
            align-items: center;
            justify-content: center;
         }
         #txtname{
            width: 100%;
            padding: 12px 20px;
            margin: 8px 0;
            display: inline-block;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
         }
         div {
            font-size:25px;
         }
      </style>
   </head>
   <body>
      <h3>Google AMP - Amp Bind</h3>
      <button on = "tap:AMP.setState({displaylightbox: true})">
         Click Here
      </button>
      <br/>
      <br/>
      <h3>
         AMP - Input Element
      <h3>
      <input id = "txtname" placeholder = "Type here" 
         on = "input-throttled:AMP.setState({name: event.value})">
      <div [text] = "name">
      </div>
   </body>
</html>

Resultado

Os dados inseridos na caixa de texto são exibidos na parte inferior. Isso pode ser feito alterando a variável de estadoname no evento de entrada como mostrado -

<input id = "txtname" placeholder = "Type here" on = 
"input-throttled:AMP.setState({name: event.value})">
<div [text] = "name">
</div>