使用Polymer扩展本机HTML元素

时间:2014-07-08 15:58:49

标签: html dom polymer web-component

您好我想从使用Polymer的本机HTML元素扩展以创建自定义Web组件。 当我没有扩展时,我的聚合物就绪回调就被调用了。一旦我延伸,就不会再调用任何东西了。虽然正在创建元素的阴影DOM ...

以下是我的用法代码:

<!DOCTYPE html>
<html>
    <head>
    <title>Custom Component Usage</title>
        <script src="bower_components/platform/platform.js"></script>
        <link rel="import" href="elements/extended-item.html">
    </head>
    <body>
        <extended-item>I was extended from div!</extended-item>
    </body>
</html>

自定义元素,扩展 div

<link rel="import" href="../bower_components/polymer/polymer.html">

<polymer-element name="extended-item" extends="div">

    <template>

        <content></content>

    </template>

</polymer-element>

<script>
Polymer('extended-item',
        {
            created: function ()
            {
                console.log('EXTENDED ITEM IS CREATED!');
            },
            ready: function ()
            {
                console.log('EXTENDED ITEM IS READY!');
            },
            attached: function ()
            {
                console.log('EXTENDED ITEM IS ATTACHED!');
            },
            domReady: function ()
            {
                console.log('EXTENDED ITEMS DOM IS READY!');
            },
            detached: function ()
            {
                console.log('EXTENDED ITEM IS DETACHED!');
            },
            attributeChanged: function (attrName, oldVal, newVal)
            {
                //var newVal = this.getAttribute(attrName);
                console.log(attrName, 'old: ' + oldVal, 'new:', newVal);
            }
        });
</script>

有什么想法吗?

提前谢谢, 罗布

1 个答案:

答案 0 :(得分:8)

如果您使用<extended-item>而不是将元素称为<div is="extended-item">,则此方法可以正常使用。

以下是一个示例(jsbin):

<polymer-element name="extended-item" extends="div">
  <template>
    <p>This is part of the template.</p>
    <content></content>
  </template>

  <script>
    Polymer('extended-item', {
      created: function() {
        console.log('EXTENDED ITEM IS CREATED!');
      },
      ready: function() {
        console.log('EXTENDED ITEM IS READY!');
      },
      attached: function() {
        console.log('EXTENDED ITEM IS ATTACHED!');
      },
      domReady: function() {
        console.log('EXTENDED ITEMS DOM IS READY!');
      },
      detached: function() {
        console.log('EXTENDED ITEM IS DETACHED!');
      },
      attributeChanged: function (attrName, oldVal, newVal)
      {
        //var newVal = this.getAttribute(attrName);
        console.log(attrName, 'old: ' + oldVal, 'new:', newVal);
      }
    });
  </script>
</polymer-element>

<div is="extended-item">I was extended from div!</div>

编辑:正如本评论所指出的,这是Custom Elements spec中记录的预期行为。