Search code examples
polymerpolymer-2.x

How to set a listener on a span element in Polymer 2.0?


I have the following code

var span = document.createElement('span');
Polymer.dom(span).setAttribute('class','right-icon dfw-remove-icon dfw-24');
this.listen(span, 'tap', '_removeIt');
return span;

This segment of code is from an older project that uses Polymer 1 but I'm trying to make an application using Polymer 2. The third line doesn't work for me on Chrome, it gives me an error saying this.listen is not a function. How would I set a listener on the span element so that it triggers _removeIt() when clicked on?


Solution

  • this.listen equvialent

    this.listen() effectively calls addEventListener(), so the equivalent of:

    this.listen(span, 'tap', '_removeIt');
    

    is:

    span.addEventListener('tap', e => this._removeIt(e));
    

    Use click instead of tap

    In Polymer 1, tap was recommended for cross-platform consistency in handling clicks/taps. However, in Polymer 2, tap is no longer recommended as the default, given the advances of modern mobile browsers. You should use click instead of tap.

    Don't do Polymer.dom(span)

    There's no need to call Polymer.dom(span) if span is an element created with document.createElement().