如何将对象文字作为聚合物属性传递

时间:2014-11-14 01:39:29

标签: javascript polymer web-component

为了单独测试我的一些聚合物自定义元素,我希望能够传递js对象文字以获取通常来自父元素的一些属性。我无法弄清楚如何做到这一点。请参阅此示例代码。如果它按照我的意愿工作,它会显示1和2彼此相邻,但它不起作用。

<script src="http://www.polymer-project.org/webcomponents.js"></script>
<link rel="import" href="http://www.polymer-project.org/components/polymer/polymer.html">

<polymer-element name="my-element" attributes="stuff">
  <template>
    {{stuff.one}} {{stuff.two}}
  </template>
  <script>
    Polymer('my-element', {
      ready: function () {
        console.log(this.stuff);
      }
    });
  </script>
</polymer-element>
<my-element stuff='{"one": 1, "two": 2}'></my-element>

3 个答案:

答案 0 :(得分:9)

如果使用空哈希初始化stuff属性,Polymer只会将JSON文本转换为对象:

Polymer('my-element', {
    stuff: {},
    ready: function () {
        console.log(this.stuff);
    }
});

如果没有这个,stuff属性将作为字符串传入。数组也是如此。

答案 1 :(得分:6)

另一种方法:

myElem.html

<link rel="import"
      href="http://www.polymer-project.org/1.0/samples/components/polymer/polymer.html">

<dom-module id="my-element">
    <template>
        <div> {{stuff.one}} {{stuff.two}} </div>
    </template>

    <script>
      Polymer({
          is: "my-element",
          properties: {
              stuff:{
                  type: Object,
                  value: {"one":"default_1","two":"default_2"}
              }
          }
      });
    </script>
</dom-module>

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="http://www.polymer-project.org/1.0/samples/components/webcomponentsjs/webcomponents-lite.js"></script>
    <link rel="import" href="myElem.html">
  </head>
  <body>
    <my-element></my-element>
    <my-element stuff={"one":"1","two":"2"}></my-element>
  </body>
</html>

结果

default_1 default_2  
1 2

答案 2 :(得分:3)

index.html
...
  <body unresolved fullbleed layout vertical>
     <my-post info='{"name":"Alex","id":"123"}' posts='[{"id":"456","name":"post1"},{"id":"789","name":"post2"}]'></my-post>  
  </body>
    ...

my-post.html 
    <link rel="import" href="../../bower_components/polymer/polymer.html">
    <polymer-element name="my-post" attributes="info posts" >
      <template>

       {{info.name}}
         <template repeat="{{post in posts}}">
              <br>   {{post.id}} - {{post.name}}
         </template>

      </template>
   <script>
    (function () {
      Polymer({
      ready: function() {
        this.info=JSON.parse(this.info)
        this.posts=JSON.parse(this.posts)
    },
   });
  })();
  </script>
</polymer-element>