如何访问绑定的Polymer数据并在脚本中使用它?

时间:2017-06-26 19:21:47

标签: javascript data-binding polymer polymer-1.0

我正在使用<firebase-document>从Firebase获取数据。我将数据绑定到{{poster}}。然后我使用该ID使用其键显示海报对象的详细信息。例如,{{poster.name}}显示海报的名称。我现在想在脚本中使用{{poster.name}}。当我console.log(this.poster.name)时,我收到undefined错误。如何访问{{poster}}绑定数据?

这是我的元素:

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/plastr-poster/plastr-poster.html">
<link rel="import" href="../bower_components/polymerfire/firebase-document.html">
<link rel="import" href="../bower_components/app-metadata/app-metadata.html">
<link rel="import" href="shared-styles.html">

<dom-module id="my-details">
  <template>
    <style include="shared-styles">
      :host {
        display: block;
      }
    </style>

    <app-route
      route="{{route}}"
      pattern="/:poster_id"
      data="{{routeData}}"
      tail="{{subroute}}">
    </app-route>

    <firebase-document
      id="firebaseDoc"
      path="/posters/[[routeData.poster_id]]"
      data="{{poster}}">
    </firebase-document>
    <app-metadata></app-metadata>

    <div class="poster_board">
      <a href="./[[routeData.poster_id]]">
        <plastr-poster id="poster" name="[[poster.name]]" location=[[poster.location]] poster="[[poster.poster]]" date="[[poster.date]]"></plastr-poster>
      </a>
    </div>
  </template>

  <script>
    Polymer({
      is: 'my-details',
      ready: function() {
        this.fire('app-metadata', {
          title: this.poster.name,
          description: "things to do in your 'hood",
          keywords: 'events, posters, local, music, dance, art'
        });
        console.log(this.poster.name);
      },
      attached: function() {
        // this will create the singleton element if it has not been created yet
        Polymer.AppMetadata.requestAvailability();
      },
      properties: {
        prop1: {
          type: String,
          value: 'plastr-app',
        },
      }
  });

  </script>
</dom-module>

1 个答案:

答案 0 :(得分:1)

您的ready处理程序似乎正在尝试访问this.poster.name,但this.poster尚未填充<firebase-document>。我会像poster.name这样使用observer

Polymer({
  // ...

  observers: ['_fireMetadataEvent(poster.name)'],

  _fireMetadataEvent: function(posterName) {
    if (posterName) {
      this.fire('app-metadata', {
        title: posterName,
        // ...
      });
    }
  }
);