Polymer 2.0数据绑定不起作用

时间:2018-03-24 07:00:41

标签: data-binding polymer polymer-2.x

我在Polymer中有一个视图,用户可以扫描QR码,数据将显示为视频预览下方的标题。这是代码。

<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="shared-styles.html">
<script type="text/javascript" src="../js/instascan.min.js"></script>

<dom-module id="my-view1">
  <template>
    <style>
      :host {
        display: block;
        text-align: center;
      }

      #preview {
        width: 100% !important;
        height: auto !important;
        border-radius: 2px;
      }
    </style>
    <!-- Video preview of camera for QR code scanning -->
    <video id="preview"></video>
    <!-- List of QR code items scanned-->
    <h1>{{bucketItems}}</h1>
  </template>
  <script>
    class MyView1 extends Polymer.Element {
      static get is() { return 'my-view1'; }
      static get properties() {
        return {
          bucketItems: {
            type: String,
            reflectToAttribute: true
          },
        }
      }

      // Once page has loaded
      connectedCallback() {
        super.connectedCallback();
        // List of items in bucket (contains scanned ingredients)
        var itemsBucket = [];
        // Scan QR Code using Instascanner
        let scanner = new Instascan.Scanner({ video: this.$.preview });
        scanner.addListener('scan', function (content) {
          // Access the QR code content using "content"
          if (!itemsBucket.includes(content)) {
            // Only add items once to the bucket
            itemsBucket.push(content);
          }
          this.bucketItems = itemsBucket.toString();
          console.log(this.bucketItems);
        });
        Instascan.Camera.getCameras().then(function (cameras) {
          if (cameras.length > 0) {
            scanner.start(cameras[0]);
          } else {
            console.error('No cameras found.');
          }
        }).catch(function (e) {
          console.error(e);
        });
      }
    }
    window.customElements.define(MyView1.is, MyView1);
  </script>
</dom-module>

当我console.log(this.bucketItems)时,我可以看到他们扫描的项目列表,但数据在h1标记中不可见。我该如何正确绑定它。我是聚合物新手,刚开始学习数据绑定。

1 个答案:

答案 0 :(得分:2)

此问题是您的回调的上下文未绑定到Polymer对象,因此它使用外部上下文。

您可以切换到箭头功能以自动绑定Polymer对象,使用:

scanner.addListener('scan', content=> {

而不是:

scanner.addListener('scan', function (content) {

DEMO