简体   繁体   中英

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 (ie, 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' }, 

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:

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