This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Create Event Listeners in Polymer Elements

1:32 JavaScript lesson by

In this lesson we'll look at creating event listeners in our custom element using the listeners object as well as annotated event listeners.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

In this lesson we'll look at creating event listeners in our custom element using the listeners object as well as annotated event listeners.

Polymer gives us a couple different ways to add event listeners. The first look we'll take is at the annotated version, which is the inline version right here on an element.

To get to our event, I'm going to say on-Click. You'll notice this is a dash syntax rather than the Hungarian notation you might be used to. I'm just going to reference a handler, so I'm going to call that clickHandler. Down here, after is, I'm going to set up clickHandler to be a function. I'm simply going to console log click. We save that, we've got our button and when we click on it, we have our event firing.

Now, the next way we can do that is with a listener on our actual Polymer instantiations, so this'll be our listener version. To reference this guy I'm going to give it an ID, let's just say Button ID.

Now, to set up a listener from within our Polymer instantiation, we add a key called listeners. It's going to be an object, and our first key for the element and event we want to assign this to is going to be our selector, so in our case, buttonID.click. That's the event, then we're simply in the string going to pass in our click handler.

We'll save that. Here on the right we've got our annotated version, we've got our click event, and then we've got our listener version. Again, you can see that our click event is firing.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?