Execute Custom Events in Polymer

We can utilize the "fire" method from within our custom element to execute a custom event. In this lesson we'll create a custom event and pass useful data along with the event to the consumer of our element.

You must be a Member to view code

00:00 Polymer allows us to generate custom events from within our component. I've got a component here or an element called my range. It's simply going to output an input with a type of range.

00:14 We're going to bind our value to a attribute called value. We're going to bind this to the on input event of our range. Here I'm just going to set up a max of 100 and a min of 0There's our component there.

00:35 Down here, we're going to set up our properties key. We're going to have a key of value. It's going to have a type of number. It's also going to have an observer. We're going to set that to handle input.

00:52 We'll go ahead and create that observer now. Handle input, this can be a function. Since it's an observer, it's going to take in a new value and an old value.

01:03 We're simply going to say if we have an old value, something that's actually changed, we're going to use this.fire. This is the mechanism that allows us to announce a custom event. We'll call this custom event value change.

01:17 We can also pass details along with that event. The way we do that is, in this second argument, we create an object. I'm going to have a key here called increased.

01:26 I'm going to set that to new val is greater than old val. If it's increasing, that'll be true. If it's not increasing or in fact it's decreasing, it will be false.

01:38 While we're in here, this should actually be a double colon. I'm going to save that.

01:43 We're going to jump over to our index.html. We're going to HTML import our my range component. We'll get that guy on the page right here. We'll go in and give that a default value of 10. We save that.

01:58 We can see that we do in fact have our component on the page. If I refresh, it is getting that default value of 10 along the scope of 0to 100. The way we can tap into the custom event is by saying, "document.query selector."

02:17 We'll just do an element selector here, so my-range. We're going to add an event listener. The event we're listening to is value changed.

02:29 We're going to have our callback function which takes in the event. The way that we can get to the event details is with e.detail. Our specific value that we're looking for is increased.

02:43 We're simply going to console log out that value. So when we increase the value, we should get a console log of true. When we decrease that value, we should get a console log of false. Save that.

02:56 We're at our 10. When I jump ahead, we get our true. When I decrease, we get our false. All along the way, we're console logging out the value that we're getting from our custom event.