3

我想用 Polymer 元素实现子父级之间的通信。

这是我的 index.html

<proto-receiver data="message">
        <proto-element data="message"></proto-element>
</proto-receiver>

两个元素都有各自的“数据”属性

properties: {
   data: {
      value: 'my-data',
      notify: true,
   }
},

在 proto-receiver 中,这是我通过处理简单的点击来更新“数据”的父级

<template>
    <span on-tap="onClick">proto receiver: {{data}}</span>
    <content></content>
</template> 


onClick: function () {
    this.data = 'new-message';
},

我希望更改也能传播到子元素,正如这里提到的那样

我通过在我的子元素中传递一个 setter 并像这样调用它来实现这一点。我猜这不是应该的方式。

 Polymer.Base.$$('body').querySelector('proto-element').setData(this.data);

我做错了什么

谢谢

更新:

对于那些来这里的人。这样做的正确方法是使用事件。

聚合物 1.x

this.fire('kick', {kicked: true});

聚合物 2.x(简单的 javascript)

this.dispatchEvent(new CustomEvent('kick', {detail: {kicked: true}}));

在这两种情况下,接收者都应该实现常规的 addEventListener

document.querySelector('x-custom').addEventListener('kick', function (e) {
    console.log(e.detail.kicked); // true
})
4

2 回答 2

4

To provide a concrete example to Scott Miles' comments, if you can wrap your parent and child elements in a Polymer template (such as dom-bind or as children to yet another Polymer element), then you can handle this declaratively. Check out the mediator pattern.

parent element:

<dom-module id="parent-el">
  <template>
    <button on-tap="onTap">set message from parent-el</button>
    <p>parent-el.message: {{message}}</p>
    <content></content>
  </template>
  <script>
    Polymer({
      is: 'parent-el',
      properties: {
        message: {
          type: String,
          notify: true
        }
      },
      onTap: function() {
        this.message = 'this was set from parent-el';
      }
    });
  </script>
</dom-module>

child element:

<dom-module id="child-el">
  <template>
    <p>child-el.message: {{message}}</p>
  </template>
  <script>
    Polymer({
      is: 'child-el',
      properties: {
        message: {
          type: String,
          notify: true
        }
      }
    });
  </script>
</dom-module>  

index.html:

<template is="dom-bind" id="app">
  <parent-el message="{{message}}">
    <child-el message="{{message}}"></child-el>
  </parent-el>
</template>
<script>
  (function(document) {
    var app = document.querySelector('#app');
    app.message = 'this was set from index.html script';
  }) (document);
</script>

JS Bin

于 2016-02-18T20:16:11.877 回答
2

我遇到了同样的问题并得到了解决方案并将其修复如下

this.fire('iron-signal', {name: 'hello', data: null});

你可以参考这个铁信号,你会得到你正在寻找的解决方案,它基本上是从任何元素到另一个元素的事件触发

希望这会帮助你 聚合物铁信号

于 2017-09-19T07:08:12.180 回答