在兄弟元素之间发送/接收事件的聚合物

时间:2017-02-02 14:09:13

标签: polymer polymer-1.0

假设我有两个兄弟元素,而<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>

谢谢!

1 个答案:

答案 0 :(得分:4)

您可以使用<iron-signals>

在一个元素中添加other_arrays.each { |i| array.include? i } 侦听器:

<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}`;
    }
  });
});

codepen