7

I have a custom element which itself hosts a custom element.

<polymer-element name="flex-nonvisual">
  <template>
    <polymer-flex-layout></polymer-flex-layout>
  </template>
</polymer-element>

Now in attached() (or some other callback) of PolymerFlexLayout I want to set the class attribute of the flex-nonvisual element.

In Javascript the code looks like this.parentNode.host.classList.add('someclass');

In Dart in attached() (after the call to super.attached()) this.parent is null and I couldn't find any other reference to the host element.

How can I do this in Dart?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 3
    A small remark: I would consider this bad practice since it breaks the encapsulation of the polymer-flex-layout component. In general, a child component should never set properties or invoke methods on a parent. The child should dispatch an event that the parent can listen to and decide to change its own properties. – Christophe Herreman Nov 14 '13 at 12:16
  • 1
    You are right, I didn't think about alternative ways. I'm currently porting polymer-elements from Javascript and just tried to do the same in Dart what they did in JS.Thank you very much for your help out of the blind lane ;-). – Günter Zöchbauer Nov 14 '13 at 14:46

2 Answers2

7

Unfortunately creation order of custom elements is not guaranteed. See the Polymer.dart discussion and the Related discussion on the Polymer discussion groups.

However as mentioned, your particular usage will break encapsulation and using CustomEvents is much more the way to go. And using Polymer this becomes very easy to implement as well.

<!-- flex_nonvisual.html file -->

<polymer-element name="flex-nonvisual">
  <template>
    <polymer-flex-layout on-ready="{{layoutReady}}"></polymer-flex-layout>
  </template>
</polymer-element>
// polymer_flex_layout.dart file

@CustomTag('polymer-flex-layout')
class PolymerFlexLayout extends PolymerElement {
  // other stuff here
  void attached() {
    super.attached();
    dispatchEvent(new CustomEvent('ready'));
  }
}
// flex_nonvisual.dart

@CustomTag('flex-nonvisual')
class FlexNonvisual extends PolymerElement {
  // Other stuff here
  void layoutReady(Event e, var details, Node node) {
    this.classes.add('someclass');
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Matt B
  • 6,192
  • 1
  • 20
  • 27
6

update: Polymer >=1.0.x

shady DOM

new PolymerDom(this).parentNode;

or

domHost

short for

Polymer.dom(this).getOwnerRoot().host   

full shadow DOM

(this.parentNode as ShadowRoot).host

@ChristopheHerreman and @MattB are still right about encapsulation should not be broken.

But also JS Polymer elements access the parent in their layout elements because it's still convenient in some scenarios.

This works now in PolymerDart too.

Polymer.dart <= 0.16.x

(this.parentNode as ShadowRoot).host
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567