This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Observe Property Changes on a Custom Polymer Element

1:57 JavaScript lesson by

Custom element property changes can be observed by specifying an observer method which will be executed whenever a change occurs and receive both the new value and old value.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

Custom element property changes can be observed by specifying an observer method which will be executed whenever a change occurs and receive both the new value and old value.

Polymer allows us to tack on an observer delegate to any of our properties. I've set up a quick little element here called observer element. Going to have an input with the type of text and its value. It's going to be bound to, we'll say, color on the on input event of our input.

I'm just going to have a simple H1 here, just going to say "Hello," and going to get back an ID of "Hello."

Now, here in our properties, of course, we're going to have our color key here. That's going to have a type of string. Then we're going to tack on our observer key.

Now, here, we can delegate the observation of any change to this property to a named function. I'm just going to go ahead and pass in color changed.

Now, unlike a notify element, this is not an automatically created call back. We do need to create this ourselves. Here's our color changed function.

As an observer, it automatically gets two values. The first one is new value, and the second one is old value. The new value being the new value for that property and the old value being the previous value.

To get a look at that, we'll just go ahead and log out new val and old val. Save that, and over here in the browser, we'll bring up our developer tools. As I type this, you can see that we are, in fact, getting the new value as well as the previous value.

We can do with that whatever we please. I'm just going to go ahead and say this.$, which is how we access the local DOM. I'm going to say "Hello," which is the idea of our element. Going to say style.color is equal to new val.

Save that and up here, if I type "red," we get red as our style.color. If I type "blue," we get blue, "green," we get green.

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