Polymer.fire 不是函数

Polymer.fire is not a function

我的 web 组件 (Polymer 1.0) 更改了 给定的 light-DOM 并尝试将点击转换为自定义事件。

<link rel="import" href="path/to/polymer.html">
<dom-module id="x-custom">
    <template>
        <content></content>
        <!-- used this way <x-custom><div></div></x-custom> -->
    </template>

    <script>
    (function() {

        function init() {
            var myRoot = Polymer.dom(this);
            var firstDiv = myRoot.querySelectorAll("div")[0];
            var itemDiv = document.createElement("div");
            itemDiv.textContent = "Yadda";
            firstDiv.appendChild(itemDiv);

            itemDiv.addEventListener("click", follow);

        }

        function follow()
        {
            console.log("follow");
            Polymer.fire("custom-event");
        }

        Polymer({
            is: 'x-custom',
            ready: init
        });

    })();
    </script>
</dom-module>

它告诉我 Polymer 没有函数 fire。调用此方法的正确方法是什么?可能这里也有一些反模式...

您需要将您的函数放在主 Polymer() 函数中。它抛出错误是因为 Polymer() 函数不在您的 init() 函数的范围内。您还需要在 Polymer() 函数中声明您在模板中使用的所有自定义属性。


像这样:

<link rel="import" href="path/to/polymer.html">
<dom-module id="x-custom">
  <template>
    <content></content>
    <!-- used this way <x-custom><div></div></x-custom> -->
  </template>
  <script>
    (function() {
      Polymer({
        is: 'x-custom',
        properties: {
          customProperty1: {
            type: String
          },
          customProperty2: {
            type: String
          }
        },
        ready: function() {
          var myRoot = Polymer.dom(this);
          var firstDiv = myRoot.querySelectorAll("div")[0];
          var itemDiv = document.createElement("div");
          itemDiv.textContent = "Yadda";
          firstDiv.appendChild(itemDiv);
          itemDiv.addEventListener("click", follow);
        },
        follow: function() {
          console.log("follow");
          Polymer.fire("custom-event");
        }
      });
    })();
  </script>
</dom-module>

Polymer 对象内部没有 fire 方法。 fire 方法在Polymer.Base 中,但除非声明原型,否则不能直接使用它,因此需要this。您可以通过打开 Dev Tools 并键入 Polymer 后跟一个点来查看所有 Polymer 属性和方法。

总之你应该使用this.fire

<dom-module id="x-custom">
    <template>
        <content></content>
        <!-- used this way <x-custom><div></div></x-custom> -->
    </template>

    <script>
    (function() {

        function init() {
            var myRoot = Polymer.dom(this);
            var firstDiv = myRoot.querySelectorAll("div")[0];
            var itemDiv = document.createElement("div");
            itemDiv.textContent = "Yadda";
            firstDiv.appendChild(itemDiv);

            itemDiv.addEventListener("click", follow.bind(this));  // notice the .bind here

        }

        function follow()
        {
            console.log("follow");
            this.fire("custom-event");
        }

        Polymer({
            is: 'x-custom',
            ready: init
        });

    })();
    </script>
</dom-module>