简体   繁体   中英

How to Set `on-tap` Behavior of </paper-button> with Javascript in Polymer

I am trying to append a paper-button to tho DOM on-the-fly with a function in Poylmer 2.x.

I would like this new button to call another function when tapped.

appendNodeToDom() {
  let prop = this.result[i]['someProperty'];
  let node = document.createElement("paper-button");
  let button = document.createTextNode(prop);

  button.ontap = this.go(); // what is the proper syntax for this?

  node.appendChild(button);
  this.shadowRoot.getElementById('buttons').appendChild(node);
}

go() {
  console.log('go');
}

Also tried:

button.addEventListener("click", this.go());
button.addEventListener("tap", this.go());

How do I set the "on-tap" behavior with Javascript in Polymer 2.x?

The thing is you're calling button the text node inside the paper-button and setting the event listener on that node which - being a Text node - doesn't fire events (apart from some exceptions ).

Also, you're passing this.go() as callback to addEventListener . This means that this.go() is executed and then the return value is passed as callback (in this case undefined because after console.log you're not returning anything). You should instead pass the identifier of the function without calling it:

addEventListener('tap', this.go);

All together:

appendNodeToDom() {
  let prop = this.result[i]['someProperty'];
  let button = document.createElement('paper-button');
  let text = document.createTextNode(prop);

  button.appendChild(text);
  button.addEventListener('tap', this.go); // Add the listener to button
  this.shadowRoot.getElementById('buttons').appendChild(node);
}

go() {
  console.log('go');
}

Just a small note: keep in mind that Polymer has a lot of tools to avoid performing direct DOM manipulation. If you just need to add a button to a list you could consider a solution where dom-repeat renders the buttons and the changes are made on the underlying array property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM