2016-06-27 46 views
1

我對聚合物和JS很新,但我一直在嘗試去適應兩者。使用this demo作爲基礎,我一直在嘗試使用霓虹動畫和按鈕單擊事件將縮小動畫附加到某些圖標上。每當我嘗試使用querySelector查找包含該按鈕的模板,它總是返回:無法用聚合物霓虹動畫設置屬性'_onButtonClick'爲空

"icon-toggle-demo.html:34 Uncaught TypeError: Cannot set property '_onButtonClick' of null" 

無論我改變我只是不能按鈕不能爲空。我不確定我在這裏錯過了什麼。

<link rel="import" href="../../polymer/polymer.html"> 
<link rel="import" href="../../iron-icons/iron-icons.html"> 
<link rel="import" href="../icon-toggle.html"> 


<dom-module id="icon-toggle-demo"> 
    <template is="dom-bind"> 
     <style> 
      :host { 
       font-family: sans-serif; 
      } 

      ; 
     </style> 

     <h3>Statically-configured icon-toggles</h3> 
     <button on-click="_onButtonClick">click me</button> 
     <icon-toggle toggle-icon="star"></icon-toggle> 
     <icon-toggle toggle-icon="star" pressed></icon-toggle> 

     <h3>Data-bound icon-toggle</h3> 

     <!-- use a computed binding to generate the message --> 
     <div><span>[[message(isFav)]]</span></div> 


     <!-- curly brackets ({{}}} allow two-way binding --> 
     <icon-toggle toggle-icon="favorite" pressed="{{isFav}}"></icon-toggle> 
    </template> 

    <script> 
     var scope = document.querySelector('template[is="dom-bind"]'); 

     scope._onButtonClick = function(event) { 
      var node = document.querySelector('toggle-icon'); 
      if (node) { 
       node.animate(); 
      } 
     }; 
    </script> 

</dom-module> 

回答

1
  • dom-bind templates只需要index.html:包含按鈕

    我的文件。在<dom-module>中,您可以使用簡單的<template>

  • register your element,你需要使用Polymer功能連同註明_onButtonClick功能這樣一個原型對象:

    Polymer({ 
        is: 'icon-toggle-demo', 
        _onButtonClick: function() { 
        ... 
        } 
    }); 
    
  • Auto-node finding讓您快速通過ID與this.$.NODE_ID訪問節點(例如,this.$.myIcon)。所以,如果你有<icon-toggle>的 「starIcon」 的ID:

    ...你可以從你的聚合物物體this.$.starIcon訪問:

    _onButtonClick: function() { 
        this.$.starIcon.animate(); 
    } 
    

你的全元素定義會看起來像這樣:

<dom-module id="icon-toggle-demo"> 
    <template> 
    <style> 
     :host { 
     font-family: sans-serif; 
     } 
    </style> 

    <h3>Statically-configured icon-toggles</h3> 
    <button on-click="_onButtonClick">click me</button> 
    <icon-toggle id="starIcon" toggle-icon="star"></icon-toggle> 
    <icon-toggle toggle-icon="star" pressed></icon-toggle> 

    <h3>Data-bound icon-toggle</h3> 

    <!-- use a computed binding to generate the message --> 
    <div><span>[[message(isFav)]]</span></div> 

    <!-- curly brackets ({{}}} allow two-way binding --> 
    <icon-toggle toggle-icon="favorite" pressed="{{isFav}}"></icon-toggle> 
    </template> 

    <script> 
    Polymer({ 
     is: 'icon-toggle-demo', 
     _onButtonClick: function() { 
     this.$.starIcon.animate(); 
     } 
    }); 
    </script> 
</dom-module> 
+0

謝謝!這在瞭解所有這些工作如何是非常重要的。直到現在還不確定這個dom-bind! – Taylor

+0

@泰勒沒問題:) – tony19

相關問題