2016-12-01 82 views
0

我正在写一个Polymer元素,它从API收集信息,并根据结果的对象键将其分发给子元素。如何在Polymer中显示父对象的信息?

my-parent元素执行ajax调用。响应如果在response()函数中获取。

我的问题是:我如何以一种方式存储接收到的信息,以便我可以将其分发并显示给子元素?

App.html

<my-parent collector="1"> 
    <h1>The Results</h1> 
    <h3><my-child name="title"><!-- should output FOO --></my-child></h3> 
    <h3><my-child name="description"><!-- should output BAR --></my-child></h3> 
</my-parent> 

我-parent.html

<dom-module id="my-parent"> 
    <template> 
    <style> 
     :host { 
     display: block; 
     } 
    </style> 
    <content></content> 
    <iron-ajax auto url="//someurl/posts/[[collector]]" handle-as="json" last-response="{{response}}" on-response="onResponse" id="xhr"></iron-ajax> 
</template> 
    <script> 
     Polymer({ 
     is: 'my-parent', 
     properties: { 
      collector: { 
      type: String, 
      notify: true 
      }, 
      response: { 
      type: String 
      } 
     }, 
     onResponse: function(response){ 
      /* WHAT TO DO HERE? */ 
     } 
     }) 
    </script> 
</dom-module> 

API结果从//someurl/posts/1

{ 
    "title": "FOO", 
    "description": "BAR" 
} 

我-child.html

<dom-module id="my-child"> 
    <template> 
    <style> 
     :host { 
     display: block; 
     } 
    </style> 
    {{itemes}} 
    </template> 
    <script> 
     Polymer({ 
     is: 'my-child', 
     properties: { 
      itemes: { 
      type: String, 
      value: function(){ 
       return "what to do here?"; 
      } 
      } 
     }, 
     key: { 
      type: String, 
      notify: true 
      } 
     }) 
    </script> 
</dom-module> 

回答

0

由于<my-child>实际上是<my-parent>的光DOM子项,而不是<my-parent>的本地DOM(即Shadow DOM)的一部分,因此您必须使用Polymer's DOM API

在我-parent.html,从<iron-ajax>删除on-response="onResponse"属性,而是更新<script>以下几点:

Polymer({ 
    is: 'my-parent', 
    properties: { 
    collector: { 
     type: String, 
     notify: true 
    }, 
    response: { 
     type: Object, 
     observer: '_handleResponse' 
    } 
    }, 
    _handleResponse: function(response) { 
    Polymer.dom(this).querySelector('[name="title"]').itemes = response.title; 
    Polymer.dom(this).querySelector('[name="description"]').itemes = response.description; 
    } 
}) 

,然后我-child.html的<script>可以更新以下内容:

Polymer({ 
    is: 'my-child', 
    properties: { 
    itemes: { 
     type: String 
    } 
    } 
}) 

虽然这可能不是您想要的,但它会告诉您如何将数据从父组件传输到其轻DOM子组。在这个例子中,我们设置了itemes的每个<my-child>属性,并且该属性被设置为将其文本值作为本地DOM文本节点呈现。

所有他这样说,我不知道这种做法将与影子DOM规范V1(有可能需要具有节点是直接孩子,那么也许有,为淡DOM儿童或地方工作/ shadow DOM子项),但对于使用Shady DOM的Polymer 1.x,它会起作用。