兄弟元素之间的 Polymer sending/receiving 事件

Polymer sending/receiving events among sibling elements

假设我有两个兄弟元素,<element-b> 触发了一个事件。 <element-a> 如何在不必向父级添加命令式代码的情况下监听事件?

<dom-module id="parent-element">
  <element-a></element-a>
  <element-b></element-b>
</dom-module>

其中 <element-a><element-b> 是:

<dom-module id="element-a">
  <template>
    <style include="shared-styles">
    </style>
  </template>

  <script>
    Polymer({
      is: 'element-a',
      listeners: {
        'element-b': 'handleEvent',
      },
      ready: function() {
        console.log('fired from element a')
        this.fire('element-a', {employee: ''});
      },
      handleEvent: function (e) {
        console.log('received element b event', e)
      }
    });
  </script>
</dom-module>

<dom-module id="element-b">
  <template>
    <style include="shared-styles">
    </style>
  </template>

  <script>
    Polymer({
      is: 'element-b',
      listeners: {
        'element-a': 'handleEvent',
      },
      ready: function() {
        console.log('fired from element b')
        this.fire('element-b', {employee: ''});

      },
      handleEvent: function (e) {
        console.log('received element a event', e)
      }
    });
  </script>

谢谢!

你可以使用 <iron-signals>

在一个元素中添加一个 <iron-signals> 侦听器:

// element-b
<iron-signals on-iron-signal-element-a="_onSignalElementA"></iron-signals>

_onSignalElementA: function(e) {
  const newDate = e.detail;
  ...
}

...并在另一个中触发一个 iron-signal 事件(带有数据):

// element-a
this.fire('iron-signal', {name: 'element-a', data: new Date()});

HTMLImports.whenReady(() => {
  Polymer({
    is: 'x-foo'
  });
  Polymer({
    is: 'element-a',
    _onClick: function() {
      this.fire('iron-signal', {name: 'element-a', data: new Date()});
    }
  });
  
  Polymer({
    is: 'element-b',
    _onSignalElementA: function(e) {
      this._message = `b received: ${e.detail}`;
    }
  });
});
<head>
  <base href="https://polygit.org/polymer+1.11.0/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="iron-signals/iron-signals.html">
</head>
<body>
  <x-foo></x-foo>

  <dom-module id="x-foo">
    <template>
      <element-a></element-a>
      <element-b></element-b>
    </template>
  </dom-module>
  <dom-module id="element-a">
    <template>
      <button on-tap="_onClick">Fire event</button>
    </template>
  </dom-module>
  <dom-module id="element-b">
    <template>
      <iron-signals on-iron-signal-element-a="_onSignalElementA"></iron-signals>
      <div>[[_message]]</div>
    </template>
  </dom-module>
  
</body>

codepen