无法设置属性' _onButtonClick'使用聚合物霓虹动画

时间:2016-06-27 17:58:23

标签: javascript polymer

我对Polymer和JS很陌生,但我一直在努力适应这两者。使用this demo作为基础,我一直在尝试使用Neon Animations和按钮点击事件将缩小动画附加到某些图标。每当我尝试使用querySelector查找包含按钮的模板时,它总是返回:

"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 个答案:

答案 0 :(得分:1)

    仅在index.html中需要
  • dom-bind templates。在<dom-module>中,您只需使用普通<template>

  • register your element,您需要将Polymer函数与具有_onButtonClick函数的原型对象一起使用,如下所示:

    Polymer({
      is: 'icon-toggle-demo',
      _onButtonClick: function() {
        ...
      }
    });
    
  • Auto-node finding允许您使用this.$.NODE_ID(例如this.$.myIcon)按ID快速访问节点。因此,如果您的<icon-toggle>的ID为“starIcon”:

    ...您可以使用this.$.starIcon

    从Polymer对象访问它
    _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>