在 Polymer 中动态创建元素并设置属性

dynamically create elements in Polymer and setting attributes

考虑定义聚合物元素

<dom-module id="custom-element"> 
  <template>
    <h1>I expect to be green</h1>
  </template>
  <script>
    Polymer({
      is: 'custom-element',
      properties: {
        color: {
          type: String,
          value: 'red'
        }
      },
      ready: function() {
        this.style.color = this.color;
      }
    });
  </script>
</dom-module>

我希望以下两个会产生相同的结果:

  1. (在标记中)

    <body>
      <custom-element color="green"></custom-element>
    </body>
    
  2. (在 JS 中)

    var customElement = document.createElement('custom-element');
    customElement.color = 'green';
    document.body.appendChild(customElement);
    

但实际上并没有,因为似乎在 customElement 附加到 document.body 之前设置了属性并触发了聚合物 'ready' 函数。

所以基本上我不能动态创建(在 JS 中)自定义元素并设置它们的初始属性,不同于默认属性。

你建议我怎么做?

谢谢!

attached 回调中设置 color 而不是 readyAttached 在元素添加到 dom 后调用。

<base href="https://polygit.org/components/">
<script src="wecomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
<dom-module id="custom-element">
  <template>
    <h1>I expect to be green</h1>
  </template>
  <script>
    Polymer({
      is: 'custom-element',
      properties: {
        color: {
          type: String,
          value: 'red'
        }
      },
      attached: function() {
        this.style.color = this.color;
      }
    });
  </script>
</dom-module>


<html>

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <script>
    var customElement = document.createElement('custom-element');
    customElement.color = 'green';
    document.body.appendChild(customElement);
  </script>
</body>

</html>

对于您的情况,我会避免更改 DOM 并使用简单的属性绑定。

这是一个概念证明:http://jsbin.com/jozejemumu/1/edit?html,js,output

如您所见,我对 h1 元素上的 style 属性使用了属性绑定,它只是将 CSS 颜色 属性 设置为任何值元素的 color 属性 是。

代码非常简单,看起来像这样:

  <dom-module id="custom-element"> 
    <template>
      <h1 style$="color: [[color]];">I expect to be green</h1>
    </template>
    <script>
      Polymer({
        is: 'custom-element',
        properties: {
          color: {
            type: String,
            value: 'red'
          }
        }
      });
    </script>
  </dom-module>

使用元素不变:

  <custom-element color="green"></custom-element>

或者:

  var customElement = document.createElement('custom-element');
  customElement.color = 'orange';
  document.body.appendChild(customElement);

只需确保 color 属性 包含有效的 HTML 颜色 name/value。