gpt4 book ai didi

javascript - polymer 阵列添加元素两次

转载 作者:行者123 更新时间:2023-12-03 04:30:46 24 4
gpt4 key购买 nike

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

最佳答案

非常简单。每次单击 addNote 时,都会创建一个事件。因此,对于每次点击,您都会创建一个新事件,当iron-overlay关闭时,该事件将与所有先前定义的事件一起被调用。这意味着,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 = "";
}
});

关于javascript - polymer 阵列添加元素两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43497785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com