Create Event Listeners in Polymer Elements

Joe Maddalone
InstructorJoe Maddalone

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 3 years ago

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

[00:01] 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.

[00:11] 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.

[00:42] 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.

[00:57] 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, That's the event, then we're simply in the string going to pass in our click handler.

[01:21] 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.