2017-04-19 62 views
0

我在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); 

+2

。停止使用函數(){},而不是do()=> {} ..那麼你不必使'var that = this'。關鍵字'this'將始終引用您期望的正確方式。所以:'this。$。dialog.addEventListener('iron-overlay-closed',(e)=> {...}' –

+0

Ok,Kuba現在可以工作,但他仍然將它添加到數組中。第三次等... –

回答

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 = ""; 
     } 
    }); 
您使用ES6