How do I listen to events for elements in Polymer 1.0?
Asked Answered
L

3

6

I want to use Polymer's UI elements (e.g., iron-icons, paper-button, etc.) without making custom elements or templates.

For example, let's say I have:

<paper-button id="my-button">Click me</paper-button>

How do I listen for the 'click' event? Simply adding an event listener to 'click' for the ID 'my-button' doesn't work.

Lili answered 11/7, 2015 at 19:36 Comment(2)
What have code have you written so far? Have you checked the docs?Breeks
I tried $('my-button').addEventListener('click', myFunc) but that doesn't work; it seems like polymer is swallowing the click event somehow? The docs say how to do it if you are declaring a new <dom-module>, but I'm not making a new module... I want to re-use <paper-button>, ideally without wrapping it in a new module.Lili
A
6

It should just work? I'm assuming you want to use Polymer UI elements in the main doc (index.html) without having to create any custom components. Say you have

<paper-button id="btn">Click me</paper-button>

in index.html. Via vanilla js,

document.querySelector("#btn").addEventListener("click", function (e) {...});

and via jQuery,

$("#btn").on("click", function (e, u) {...});

p/s: I'd write a quick jsbin as a demo, but rawgit seems to be having issues, and I'm not aware of alternative CDNs that host Polymer Elements.

Let me be clear: Polymer elements, and by extension web components, are designed to be framework-agnostic and, if properly coded, will work on their own - just like any other HTML element. Please do not dom-bind for the sake of dom-binding. You only do so if you a) require Polymer's sugaring (like data-binding) in your use-case; and b) you want to use Polymer's sugaring from your index.html - if you don't, please don't add additional complexity to your app.

I've found a cdn serving polymer elements, so:

Look, no dom-bind and elements are working with vanilla js.

Look, no dom-bind and elements are working with jQuery.

Absorption answered 12/7, 2015 at 8:12 Comment(2)
You'll probably also want to wrap your code in index.html in a <template is="dom-bind"></template> tag. See here for details.Breeks
No, it's optional. Wrap with dom-bind only if you want to use Polymer's sugar (eg data-binding, observers, listeners, on-* events etc). Web components are generally designed to work on their own - like any other HTML element.Absorption
H
3

You can try:

<template is="dom-bind" id="t">
<paper-button id="my-button" on-click="buttonClicked">Click me</paper-button>
</template>

<script>
var template = document.querySelector('#t');
template.buttonClicked= function () {
				alert("he clicked me :)");

			};
</script>
Homophone answered 26/7, 2015 at 13:25 Comment(0)
U
1
$( "body" ).delegate( "#my-button", "click", function() {
   alert();
});
Uranian answered 27/8, 2015 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.