Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Observe Property Changes on a Custom Polymer Element

    1.2 - 1.11

    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.