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

Already subscribed? Sign In

Autoplay

    Observe Property Changes on a Custom Polymer Element

    Joe MaddaloneJoe Maddalone

    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.

    polymerPolymer
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    00:00 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.

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

    00:31 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.

    00:43 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.

    00:53 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.

    01:04 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.

    01:18 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.

    01:33 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.

    01:48 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.

    Discuss

    Discuss