"Doubling Up: The Art of Adding Elements to a Polymer

I am currently working on a to-do application using Polymer 2.0. One issue I'm facing is that when I add a note, it adds it as expected. However, when I try to add another note, it duplicates the notes in the array. I am having difficulty pinpointing the source of this problem. Additionally, I am using var that = this in my code. Is there a cleaner way to achieve the same functionality?

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

Answer №1

It's quite straightforward. Whenever you click on addNote, a new event is generated. Each click results in the creation of a new event, which is then triggered along with all previously defined events when the iron-overlay is closed. This leads to multiple calls to the callback function in addEventListener.

Simply place this code within the ready function:

   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 = "";
        }
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to link this interval service with a view component?

Exploring the AngularJS documentation for $interval, I came across an interesting example demonstrating how to utilize $interval in a controller to create a user-friendly timer in a view. The official example code can be found on the angularJS documentatio ...

Troublesome Issue with ngAnimate and ngHide: Missing 'ng-hide-animate' Hook Class

I am working on a case where I need to add animation to a DOM object using the ngHide directive: Check out this example here Within this scenario, I have an array of JSON objects: $scope.items = [ {"key": 1, "values": []}, {"key": 2, "values": [ ...

The ENOENT error code 4058 occurred while attempting to create a new react application using

Every time I run the command npm create-react-app my-app, I encounter an error like this: npm ERR! code ENOENT npm ERR! syscall spawn C:\Windows\System32; npm ERR! path C:\Users\Administrator\Documents\th-wedding\templa ...

Issues encountered when using Three.js raycasting to position objects above a plane

My heightmap-based plane is not working with raycasting, and I'm also having trouble placing an object above the hovered triangle. UPDATE: By commenting out the height section (pgeo.vertices[i].z = heightmap[i] * 5;), it seems to work inconsistently. ...

What is the best method to add an overlay div onto another div when hovered, with a grid-style layout?

I attempted to create a grid-like design where each div would display an overlay on hover. The overlay div includes two buttons that should be centered. Although I believe the logic of my code is correct, the position of the buttons and overlay is not ce ...

Placing a group of input fields and a button based on the data-id attribute of the element

I have a form that appears when a button is clicked, and the save button saves input values into an object. Is there a more efficient way to write this function if I need to create 9 more buttons with different data-id attributes (e.g. data-id="2" and so ...

Verifying if any of the entries in a specific index contain a null value

Here is the structure I am working with: { "subs": [ { "status": "1", "run_settings": null, "ward": "/asda/asd/ada" "value": null, "name": null }, { "status": "0", "run_settings": null, "ward": ...

Having trouble getting a JS file to work with the Laravel Inertia.js and Vue.js3 template

Just getting started with inertia.js and facing an issue. My CSS styles are being applied, but my JavaScript file isn't functioning as expected. I'm working on an admin dashboard using Laravel 9 and vue.js-3 with a custom HTML template. Interes ...

What is the proper way to safely close the pg-promise connection in a node.js environment once all jest tests are completed?

I am facing a challenge in closing a PG-Promise database connection after running a function test in Jest. The database connection is initialized in one central location (db.js) and required in multiple places. In this scenario, it is being used by seed.j ...

Utilize Mongoose to seamlessly integrate online shopping cart items into MongoDB

I am facing an issue while trying to insert a shopping cart of items in the form of a JSON object into a MongoDB collection using a mongoose schema. Although the customer's ID is successfully stored (extracted from the User DB), unfortunately, the ca ...

I want to create a feature where a video will automatically play when a user clicks on a specific item in a list using Angular

Currently, I'm working on a project that involves displaying a list of videos and allowing users to play them in their browser upon clicking. The technology stack being used is Angular 2. Below is the HTML code snippet for achieving this functionalit ...

Is there a way to locate all items that satisfy a specific criterion within JSON Data?

Utilizing data from an API-Call, I have established a many-to-many relationship - illustrated with the examples of people and movies. Multiple individuals can watch one movie, and one person can view several movies. In the Angular Frontend, when a person ...

Encountering Errors with Angular JS Following Update from Version 1.1.0 to 1.1.1

After upgrading, I noticed that the ng-repeat function is taking significantly longer to load and is attempting to display additional content boxes without serving the actual content provided by $resource. I have pinpointed the issue to the update from ve ...

Incorporate a "Back" button following the removal of the navigation bar in a Meteor-Ionic

When working on a Meteor-Angular-ionic app, I encountered a situation where I needed to hide the nav-bar in a template to create a full-screen view using the following code: <ion-view hide-nav-bar="true"> However, I then faced the challenge of addi ...

Tips for ensuring an HTML element remains within defined boundaries

Currently working on a visualization tool for search algorithms using React, I've encountered a minor issue when moving the start or end nodes. Upon clicking and dragging the mouse across the grid, the nodes adjust accordingly until reaching the grid& ...

What is the best way to process certain arrays of bytes within a function using "params"?

Here is a function that I have recently created: public static Mp3FileReader GetSoundsFromFiles(byte[] bytes) { return new Mp3FileReader(new MemoryStream(bytes)); } However, I am now facing a challenge where I need to parse multiple byte arrays with ...

Utilize jQuery to interact with a Web API web service

Okay, so go ahead and roast me in 27 different languages if you want, but here's my dilemma: I've delved into creating a web service using the .NET 4 Web API. I've coded a method named GetTransaction that simply returns a string. It's ...

Choose specific columns from distinct tables and arrange them accordingly

I am facing a challenge with my MySQL database as it contains multiple tables with similar columns, and I want to import this data into a Google spreadsheet. For instance: table1 has id, name, page, and other specific columns. table2 also includes id, n ...

"Triggering a JavaScript event when pasting text on

How can I capture a paste event on an iPhone using JavaScript and jQuery? I've already tried using jQuery's keyup and paste methods without success. Any suggestions? Here is the code I have attempted: $("#MyInputFields input").eq(0).b ...

Transport the unique identifier of the table row

After retrieving the list of followers from Instagram and storing it in an array in a session, I am displaying the data in a tabular format. <table class="tablesorter" cellspacing="0"> <thead> <tr> <th>&l ...