Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parent model from polymer component

Tags:

dart

I have my-app as main application component in index.html file and uses model.dart as its model which is my application model.

my-app has my-component as its content. When user interacts with my-component, I need to update values in model.dart.

<my-app>
   <my-component></my-component>
</my-app>

one approach I thought is to access my-app in my-component dart file and use its model property to access model.dart.

Is this the right approach to access model of the application? Also how to get my-app from within my-component?

like image 621
Tusshu Avatar asked Dec 03 '13 00:12

Tusshu


2 Answers

I would submit that having the child component have awareness of its parent is not a particularly good pattern.

But you are right, often what happens in the child component changes a value in the parent, or in a model bound to the parent. For cases like these, I have found that the child can dispatch an event, and the parent can choose to interact with that event as it sees fit.

Dispatching an event is as simple as doing the following (this is class MyComponent):

dispatchEvent(new CustomEvent('foo'));

And the parent can listen for that event like this:

<my-app>
  <my-component on-foo="{{someMethodOnTheParent}}"></my-component>
</my-app>

In effect, the child simply broadcasts that something has happened, but has no control over how (or even if) the parent responds. If <my-component> is used by a different parent, that parent could choose to respond to the custom event in a different way:

<another-element>
  <my-component on-foo="{{someOtherMethod}}"></my-component>
</another-element>

The callback that is triggered in parent could do pretty much anything, including modifying the model.

Hope that helps.

like image 53
Shailen Tuli Avatar answered Oct 01 '22 13:10

Shailen Tuli


Dart Polymer >= 1.0.0-x new PolymerDom(this).parentNode

See also https://www.polymer-project.org/1.0/docs/devguide/local-dom.html

Dart Polymer <= 0.16.x

@ShailenTuli is 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.

(this.parentNode as ShadowRoot).host
like image 25
Günter Zöchbauer Avatar answered Oct 01 '22 11:10

Günter Zöchbauer