5

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?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Tusshu
  • 1,664
  • 3
  • 16
  • 32

2 Answers2

6

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.

Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51
  • I agree with your comment on the design pattern but it is necessary to call component to do some work and return results to caller. I am attempting to build medical records system and there is patient search component that user uses to search for patient and the result is returned to main app. I used your suggestion but modified a little. – Tusshu Dec 03 '13 at 15:17
  • my-component is created dynamically so I could not register event handler in HTML. Instead, I defined a function in my-component that takes a function as a parameter and in my-app, after creating my-component, I set the function that is executed in my-component. – Tusshu Dec 03 '13 at 15:17
1

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
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567