聚合物和WebComponentsReady事件

17
根据Polymer文档WebComponentsReady事件是必要的,因为polyfills会异步解析元素定义并处理它们的升级。如果您过早地从DOM中获取该元素而没有等待其升级,您将使用HTMLUnknownElement进行操作。在这种情况下,在与元素交互之前,请等待WebComponentsReady事件。

我有一个HTML页面,导入单个Web组件并注册了一个处理程序,在所有Web组件加载完成时记录声明。

<!DOCTYPE html>
<html>
    <head>
        <script src="bower_components/platform/platform.js"></script>
        <link rel="import" href="elements/my-element.html">
    </head>
    <body unresolved>
        <my-element></my-element>
        <script>
            window.addEventListener('WebComponentsReady', function(e) {
                console.log('components ready');
            });
        </script>
    </body>
</html>

为什么WebComponentsReady事件在my-element的ready Polymer事件之前触发?我需要知道何时可以与自定义元素交互,例如更改其属性和调用其公共方法。

1个回答

23
在 Polymer 1.0 中,你只需监听 WebComponentsReady
在 Polymer 0.5 中,由于它执行更多异步操作,有一个额外的事件叫做 polymer-ready,当你的元素加载完成时会触发该事件。这里有一个 显示顺序的 jsbin

太好了,感谢提供的信息。运行完美。 - bitpshr
值得一提的是,由于OP中提到的原因,CustomElements polyfill仍然会触发WebComponentsReady事件。当单独使用CustomElements polyfill时,这非常有用。此外,值得一提的是,Polymer使用单独的polymer-ready事件主要是为了支持使用远程样式表而不出现FOUC的组件。 - Scott Miles
我也遇到了同样的问题,但是因为我在 polymer-ready 触发后插入了自定义元素,所以我无法使用它,需要监听单个元素的 ready 事件。不幸的是,在那时这些元素没有 ready 函数 (例如 myElement.ready(doSomething())),因为 polyfills 后添加了这些方法。我该怎么解决这个问题? - Iman Mohamadi
4
现在只有WebComponentsReady被触发。 - Nikolay Tsenkov
2
继@Nikolay所提到的,Polymer 1.0 移除了polymer-ready事件,现在你只需要监听WebComponentsReady - rajsite

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接