为什么我需要addEventListener为我的原型元素,而不是我的dom元素在聚合物



所以我通过Firefox浏览器学习聚合物,我遇到了聚合物未定义的错误。在研究SO时,我看到我必须在addEventListener函数中包装我的脚本。


<link rel="import"  href="https://polygit2.appspot.com/components/polymer/polymer.html">
<script>
  // register a new element called proto-element
  //This example needs this eventlistener
  addEventListener('WebComponentsReady', function() {
  Polymer({
    is: "proto-element",
    // add a callback to the element's prototype
    ready: function() {
  this.textContent = "I'm a proto-element. Check out my prototype!"
    }
});
})
</script>


现在当我在浏览器中运行它时,它工作得很好。当转到DOM元素时,我的脚本似乎不再需要在addEventListener()中包装。

<dom-module id="dom-element">
 <template>
    <p>I'm a DOM element. This is my local DOM!</p>
 </template>
<script>
   //for some reason this example does not 
   //addEventListener('WebComponentsReady', function() {
  Polymer({
    is: "dom-element"
  });
//})
</script>
</dom-module>

所以我的问题,为什么我的原型元素需要addEventListener函数,而我的dom模块不需要?

这种行为可以用web组件的填充来解释,(在这一点上)Firefox仍然需要这些组件。特别是,HTML导入需要填充,这是由webcomponents-lite.js脚本完成的(在您的示例中缺少)。

在您的第一个示例中,您实际上不必等待WebComponentsReady事件来调用Polymer()函数,而是等待HTMLImportsLoaded事件。因为,在点,浏览器知道如何处理链接标签:<link rel="import" href="https://polygit2.appspot.com/components/polymer/polymer.html">。然后导入聚合物库,您可以调用Polymer()。看看这个JSBin是如何工作的。

在第二个示例中,浏览器起初不知道如何处理<dom-module>,因为这是来自Polymer库的元素,而不是HTML规范的一部分。因此,<dom-module>只有在触发htmlports事件后才可用。一旦填充开始,<dom-module>将被升级,模板将被渲染,并执行其中的脚本。换句话说,没有必要显式地等待此事件,因为升级只能在事件触发后发生(或者如果它是本地支持的,如Chrome)。

这是我的解释,但也许聚合物团队可以进一步澄清…

最新更新