聚合物2中的组件初始化顺序

时间:2019-04-01 08:54:39

标签: polymer web-component polymer-2.x polymer-3.x

我们正在将中型应用程序从聚合物1迁移到聚合物3。到目前为止,我们还停留在使混合组件正常工作的中间步骤中。

我们正在考虑有关组件初始化时间的一些困难。例如:

<my-app>
  <my-component slot='componentslot'><my-component>
</my-app>

似乎在某些情况下my-component在初始化my-app之前被初始化。 my-component可能是阴影域或光域的一部分,但可能有所不同。

我们有很多紧密耦合的组件,这些组件取决于确定性的初始化顺序。例如,有一个树状结构,其中每个边缘和每个叶子都使用事件来发现它在树中的深度。因此,我们需要在内部组件之前初始化顶级元素。

但是,到目前为止,我们发现的基本上是:组件的任何初始化顺序都没有任何保证。

是否存在解决此问题的既定模式?聚合物3是否可以解决此问题(因此我们还是不需要在意)?

修改

有人要求我提供一些更具体的例子

示例1

<my-layout>
  <my-complex-component id="1">
    <my-reuseable-part/>
  </my-complex-component>
  <my-complex-component id="2">
    <my-reuseable-part/>
  </my-complex-component>
  <some-other-component>
    <my-reuseable-part/>
  </some-other-component>
</my-layout>

我有一些可重用的组件,需要知道它们是否在my-complex-componentsome-other-component内部。 my-complex-component使用context-discovery-behavior触发包含回调的事件作为有效负载。 my-complex-componentsome-other-componentcontext-behavior个侦听该事件并通过调用回调来应答的事件。

但是由于可能在附加my-reusable-partmy-complex-component之前附加了some-other-component,所以该模式不起作用。

attached(即connectedCallback)中完成事件监听器的注册以及触发转移事件。

示例2

<my-tree>
  <my-tree-edge>
    <my-tree-edge>
      <my-leaf/>
      <my-tree-edge>
        <my-leaf/>
      </my-tree-edge>
    </my-tree-edge>
    <my-tree-edge>
      <my-leaf/>
    </my-tree-edge>
    <my-leaf/>
  </my-tree-edge>
</my-tree>

在上面的示例中,每个叶子和边缘都需要知道其嵌套深度。同样,每个元素都会触发一个事件,其父元素将回答该事件。再次在attached / connectedCallback中完成侦听器注册和事件触发。如果在连接父节点之前附加了内部节点,则机械故障再次发生。

希望这会有所帮助。

1 个答案:

答案 0 :(得分:0)

如果您确实要确保首先渲染dom-if,则可以使用my-app元素,然后可以让my-component渲染如下:

<my-app ready="{{myAppReady}}>
  <template is='dom-if' if="[[myAppReady]]">
    <my-component slot='componentslot'><my-component>
  </template>
</my-app>

在我的应用脚本中:

static get properties(){return {
      ready:{type:Boolean,
             notify:true,
             value:false 
}}

在这一部分,您可以添加computed:"checkThisValuesToBeSUre(x,[y]..)以确保是否依赖于某些值,或者可以添加各种条件以呈现my-component

此外,您可以像这样动态导入my-component.js

my-app的父脚本中:

static get observers(){return ['_checkMyAppReady(myAppReady)']}

_checkMyAppReady(r){
   if(r) import('./my-component.js');
}

编辑

如果有很多元素发生相同的问题,那么最好使用lazy-import.js

_checkMyAppReady(r){
   if(r) import('./lazy-import.js');
}

lazy-import.js

import './my-component.js';
import './my-component2.js';
import './my-component3.js';
...
相关问题