Search code examples
javascriptpolymermaterial-designdom-events

Polymer.js attach handler to paper-button in standard HTML Dom


I have four buttons and trying various ways of attaching the handler declaratively:

<paper-button id="btnEnter" class="enabled" raised roll="button" on-tap="lm.LoaderActionEnter">Enter</paper-button>
<paper-button id="btnRW" class="disabled" raised roll="button">
    <core-icon icon="av:fast-rewind" on-tap="lm.LoaderActionRW()"></core-icon>
</paper-button>
<paper-button id="btnPause" class="enabled" raised roll="button">
    <core-icon icon="av:pause-circle-outline" onclick="lm.LoaderActionPause()"></core-icon>
</paper-button>
<paper-button id="btnFF" class="disabled" raised roll="button">
    <core-icon icon="av:fast-forward" on-tap="{{lm.LoaderActionFF}}"></core-icon>
</paper-button>

The only one that works is the standard onclick="handler()". I assume that on-tap="handler" would be the way to go? The above code in in a normal index.html page, within the regular flow of the page. The Javascript and polymer code is lazy loaded after the main page has rendered (splash page).

What is the best way to do this? I have only found demos that use "{{handler}}", but how would you set up the data binding?


Solution

  • The on-tap="{{handler}}" syntax is Polymer specific; it's only going to work inside the template of a Polymer element or in an auto-binding template.

    The onclick attribute works because it's built into the DOM, but we usually recommend against using the click event because it introduces a lag time on some mobile browsers.

    So if you're not using an auto-binding template for your index page, I'd recommend doing it imperatively, instead:

    Polymer.addEventListener(document.getElementById('btnEnter'), 'tap', lm.LoaderActionEnter);

    You may ask, why Polymer.addEventListener instead of just addEventListener? This is convenience method related to the Polymer gesture library, which generates the tap gesture.

    Calling Polymer.addEventListener makes sure that everything is set up correctly to generate the required event. (For example, for some browsers you may need to specify the touch-action CSS property to receive raw touch events.)

    Event handlers registered declaratively using on- handlers automatically go through this path, so most of the time when you're using Polymer, you don't need to invoke Polymer.addEventListener directly.