如何访问聚合物中的属性值?

时间:2015-07-11 22:11:45

标签: javascript polymer polymer-1.0

HTML

<my-element username="{{params.username}}"></my-element>

元素

<dom-module id="my-element">
  <style>
    :host {
      display: block;
    }
  </style>
  <template>
  </template>
  <script>
  (function() {
    Polymer({
      is: 'my-elemnt',

      ready: function(){
        // get attribute value
      });
  })();
  </script>
</dom-module>

我可以从模板访问该属性,但不知道如何从javascript访问。

2 个答案:

答案 0 :(得分:3)

在元素内部this.username但您可能需要将其添加到属性才能使其工作

 Polymer({
   is: 'my-element',
   properties: {
     username: {
       type: Object,
       observer: '_updateUsername'
     }
   },
   _updateUsername: function () {
     // use this.username
   }
 });

答案 1 :(得分:1)

<link rel="import" href="polymer/polymer.html"/>
<dom-module id="my-element" username>
    <style>
        :host {
            display: block;
        }
    </style>
    <template>
        <p>{{username.name}}</p>
    </template>

</dom-module>
<script>
    (function () {
        Polymer({
            is: 'my-elemnt',
            properties: {
                username: {
                    type: Object,
                    notify: true
                }

            },
            ready: function () {
                console.log(this.username);
            }
        });
    })();
</script>

如果您尚未声明该属性,它将记录 - undefined
有关新申报方式检查的更多信息 - https://www.polymer-project.org/1.0/docs/devguide/properties.html