且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从聚合物组件访问父模型

更新时间:2023-10-05 23:24:22

我会提交子组件有意识到它的父母不是特别好的模式。

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.

分派事件与执行以下操作一样简单(这是 class MyComponent ):

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>

实际上,孩子只是广播发生了什么事,如果)父响应。如果不同的父项使用< my-component> ,则该父项可以选择以不同的方式响应自定义事件:

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.

希望有帮助。