聚合物阵列添加元素两次

时间:2017-04-19 13:53:36

标签: javascript arrays polymer

我正在使用Polymer 2.0进行待办事项。问题是当我添加注释时。它会像它应该添加的那样,当我添加另一个时,他会向数组写入2个音符。我无法找到问题所在。我也使用var that = this。不能做任何清洁工吗?

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/app-layout/app-layout.html">
<link rel="import" href="../bower_components/iron-icons/iron-icons.html">
<link rel="import" href="../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="../bower_components/paper-button/paper-button.html">
<link rel="import" href="../bower_components/paper-dialog/paper-dialog.html">
<link rel="import" href="../bower_components/paper-input/paper-input.html">

<dom-module id="note-app">
<template>
<app-header reveals>
  <app-toolbar>
    <div main-title>Note</div>
    <paper-icon-button icon="delete" on-tap="deleteAllNotes"></paper-
     icon-button>
    <paper-icon-button icon="refresh"></paper-icon-button>
    <paper-icon-button icon="add" on-tap="addNote">+</paper-icon-
    button>
  </app-toolbar>
</app-header>

<paper-dialog id="dialog">
  <h2>Add a new note</h2>
  <paper-input id="title" label="Title of the note"></paper-input>
  <paper-input id="note" label="Content"></paper-input>
  <div class="buttons">
    <paper-button dialog-dismiss>Cancel</paper-button>
    <paper-button dialog-confirm autofocus>Accept</paper-button>
  </div>
</paper-dialog>

<template is="dom-repeat" items={{notes}}>
  <div>#: [[index]]</div>
  <div>Title: [[item.title]]</div>
  <div>Title: [[item.note]]</div>
</template>

class NoteApp extends Polymer.Element {
  static get is() { return 'note-app'; }
  static get properties() {
    return {
      notes: {
        type: Array,
        value: [],
        notify: true,
      }
    }
  }

  ready(){
    super.ready();
  }

  addNote(){
    var that = this;
    this.$.dialog.open();
    this.$.dialog.addEventListener('iron-overlay-closed', function(e){
        if(e.detail.confirmed == true){
          that.push('notes', {title: that.$.title.value, note: that.$.note.value})
          that.$.title.value = "";
          that.$.note.value = "";
        }
    });
  }

  deleteAllNotes(){
    this.splice("notes", 0, this.notes.length)
  }
}

window.customElements.define(NoteApp.is, NoteApp);

1 个答案:

答案 0 :(得分:1)

Prety简单。每次单击addNote时,都会创建一个事件。因此,对于每次单击,您都会创建一个新事件,当铁叠加关闭时,该事件与所有先前定义的事件一起调用。这意味着,addEventListener中的回调被多次调用。

将此代码移到ready函数:

   this.$.dialog.addEventListener('iron-overlay-closed', function(e){
        if(e.detail.confirmed == true){
          that.push('notes', {title: that.$.title.value, note: that.$.note.value})
          that.$.title.value = "";
          that.$.note.value = "";
        }
    });