问题
I have a basic Polymer template with a very simple structure, described here:
Polymer: can't get this.__data__ passing in from host (codebase is here: https://srgg6701.github.io/Polymer_template)
I need to use data passed from parent to children. I can pass them and see it within this.domHost
:
However, if I try to get this.domHost.properties
, it says undefined
(!).
So, two questions:
- Why it is undefined here?
- Is it possible to make this data accessible?
回答1:
For Question#1: It's most likely copy of the element before the ready event, thats why it is undefined. Most of the cases you should use the Polymer DOM API to manipulate in the DOM. The Host Object should be available in: Polymer.dom(this).getOwnerRoot().host
For Question#2: Use Polymer Data Binding for this kind of job what you want achieve. You can still use the this.policies
in the parent element, but the Data Binder will give information to the child elements and everything will be synchronized and handled.
For the data binding, add a property to your x-comphost
and x-child
element:
properties: {
data: {
type: Object,
value: null, // Default Value
// Fire value-changed Event when changed
// so the elements and the data binding
// will react to that.
notify: true
// (optional) Listener for the property changing
// if your want to make custom logic
observer: '_doSomething'
}
}
And in themplate add the attribute like this: <x-child data="{{data}}"></x-child>
With more elements you can make a Behavior which can contain the property and the observer details and you not need to copy-paste to every element but you can override if you want:
var MyDataBehavior = {
properties: {
data: {type:Object, notify:true, observer: '_dataChanged'}
},
dataChanged: function( data ) { /* ... */ }
};
After you added the behavior input then just add it to your element definition:
//...
behaviors: [MyDataBehavior],
//...
Shadow DOM is similar a closed Castle where you cannot enter or leave from inside, you have to build bridges to let peoples in and out.
Monica Dinculescu (from Google Polymer team):
Make bridges instead of dragons to enter the Shadow DOM castle!
Ultimatley you can add your data into the global scope and you can reach it, because the window object is shared, not some kind of copy of the original one.
来源:https://stackoverflow.com/questions/39544607/how-to-get-polymer-domhost-property