Search code examples
javascriptpolymerpolymer-1.0web-componentgoogle-web-component

Polymer Lifecycle: Why are properties not yet loaded from DOM attributes at 'Attached' callback?


I have a really hard time understanding polymer element lifecycles.

Suppose I have a custom element with a single property fooBar. And suppose I set fooBar as an attribute on the attribute like so.

<custom-element foo-bar="text"></custom-element>

Now let's say I'd like to use fooBar programmatically as a property during the element lifecycle creation. So something like.

Polymer({
    is: "custom-element",
    properties: {
        fooBar: {type: String}
    },
    ready: function(){
        console.log(this.fooBar)
    }, 
    attached: function(){
        console.log(this.fooBar)
    }
})

So far as I can tell, the element property fooBar isn't loaded from the DOM attribute fooBar until after both ready and attached are called. This holds true even when I call async from inside the ready and attached callbacks.

Can anyone explain (1) where in the lifecycle the element properties are imported from the DOM attributes and (2) how to programattically access those attributes to do some setup work on the element?


Solution

  • If you've read about the Custom Element Spec, there is this callback in an element's lifecycle called attributeChangedCallback(name, oldVal, newVal) where it's conveniently renamed in Polymer as attributeChanged(type, name). However, this is not the preferred way of listening to attributes, instead you attach an observer to that property, in this case on fooBar.

    Here's a jsbin sample. You can see that fooBarChanged is being called first before attached and ready.

    http://jsbin.com/gibopu/edit?html,console,output