首页 > 解决方案 > 聚合物路由观察器 - 导致逻辑问题的多个实例

问题描述

使用聚合物 1.*

我有foo-bar一个有两个实例的元素。

<foo>
  <apple-pie>
    <foo-bar></foo-bar>
  </apple-pie>
</foo>

<bar>
  <cherry-pie>
    <foo-bar></foo-bar>
  </cherry-pie>
</bar>

element foo-bar 有一个路由变化的观察者:

  <app-location route="{{route}}"></app-location>

   observers: ['_routeChanged(route.path)'],

    _routeChanged: function(newValue) {
      if (this.route.path.indexOf('main') > 0 &&
        this.firstLoadComplete &&
        this.oldRoutePath !== this.route.path) {
        this.cancel();
      }
      this.oldRoutePath = this.route.path;
    },

我遇到的问题是_routeChanged每次路由更改为每个实例触发两次。这意味着this.cancel()触发两次......每个元素一个,这对我来说是个问题。

当路线改变时,我怎样才能this.cancel只为实际活动的元素开火?

标签: polymerpolymer-1.0

解决方案


当路线改变时,我怎样才能让 this.cancel 只为实际活动的元素触发?

您究竟是如何检查哪个元素实际上是“活动的”?

您可以让宿主元素控制布尔标志来指定哪个是活动的,或者将它双向绑定到父元素并在那里有逻辑来说明它是否处于活动状态:

<foo active={{fooActive}}>
  <apple-pie>
    <foo-bar active={{fooActive}}></foo-bar>
  </apple-pie>
</foo>

<bar active={{barActive}}>
  <cherry-pie>
    <foo-bar active={{barActive}}></foo-bar>
  </cherry-pie>
</bar>

然后,将其添加到 foo-bar 元素:

  <app-location route="{{route}}"></app-location>

   observers: ['_routeChanged(route.path)'],

    _routeChanged: function(newValue) {
      if (this.route.path.indexOf('main') > 0 &&
        this.firstLoadComplete &&
        this.oldRoutePath !== this.route.path &&
        this.active) {
        this.cancel();
      }
      this.oldRoutePath = this.route.path;
    },

推荐阅读