Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymer 1.x: Imperatively adding event listener

I have added an event listener to my custom element for my <iron-ajax> call.

Question

Is there a shorter (more convenient syntax) way to imperatively (i.e., using Javascript) add the event listener in Polymer?

In other words, does the Polymer library contain any syntax sugaring for this?

custom-element.html
<template>
  ...
  <iron-ajax id="ajax" last-response="{{ajax}}"></iron-ajax>
  ...
<template>
<script>
  ...
  var that = this,
  t = this.$.ajax;
  t.addEventListener('response', function(e) {
    console.log(that.ajax);
  });
  ...
</script>

Research

The documentation here says:

You can also add an event listener to any element in the this.$ collection using the syntax nodeId.eventName.

But I think this only applies when using the listeners property in the Polymer object as in:

listeners: {
  'tap': 'regularTap',
  'special.tap': 'specialTap'
},
like image 277
Let Me Tink About It Avatar asked Sep 25 '22 20:09

Let Me Tink About It


1 Answers

What should work in JS as well (only tried in Dart)

 this.listen(this.$.ajax, 'last-response', 'lastResponseHandler');

there is also this.unlisten() to cancel the event subscription. I assume that if you add it imperatively, you also need to remove it imperatively to prevent memory leaks.

References:

  • listen
  • unlisten
like image 122
Günter Zöchbauer Avatar answered Oct 11 '22 10:10

Günter Zöchbauer