Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 204
tigeroctopus Avatar asked Jul 11 '15 19:07

tigeroctopus


3 Answers

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.

like image 168
zerodevx Avatar answered Oct 23 '22 09:10

zerodevx


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>
like image 26
RosAng Avatar answered Oct 23 '22 07:10

RosAng


$( "body" ).delegate( "#my-button", "click", function() {
   alert();
});
like image 1
Ryann Galea Avatar answered Oct 23 '22 08:10

Ryann Galea