【问题标题】:Event Handling between parent and child page in polymer 1.0聚合物 1.0 中父子页面之间的事件处理
【发布时间】:2015-08-03 07:56:52
【问题描述】:

我有一个称为 parent-page 的父聚合物元素和一个称为 child-page 的子元素。

parent-page 调用子页面并传递一个数组。例如,在父页面中:

<child-page items={{itemsArray}}></child-page>

现在,基于某些活动,子页面会触发一个带有新数组的事件。

例如,在子页面中:

this.fire('eventPerformed', newArray);

父页面正在侦听此数组并收到预期值。 现在,我想将该新数组传递给子页面,以便根据新数组呈现子页面。

如何实现?

编辑:我的子页面如下所示。

<dom-module id="child-page">

<style>
	
</style>

<template>
	
	<template is="dom-repeat" items="{{itemArray}}" as="fooditem">
							
		<div class="horizontal layout">
			<div>{{fooditem.quantity}}</div>
			<div>{{fooditem.name}}</div>
		</div>
	
	</template>
	<paper-button on-click"changeArray"> ChangeArray</paper-button>
	
</template>
	
<script type="text/javascript">

	Polymer({
		is:'child-page',
		properties:{
			itemArray:Array	
			},
		changeArray:function(){
			this.itemArray=<<Some new Array>>
             this.fire('eventPerformed',newArray);


		}
	});

</script>

</dom-module>

有什么方法可以在同一个子页面中使用新数组调用模板重复?还是我必须向父页面触发事件并再次调用子页面?如何实现?

【问题讨论】:

  • 但是子页面已经有数据了,不是吗?
  • 好吧,你的意思是,我不应该触发这个事件?那么如何根据更改后的数组重新渲染相同的页面呢?
  • 如果你有数据 (newArray) 为什么不简单地更新你的属性?
  • 是的,有点奇怪你会向父级触发一个事件,只是让它重新通知更新数组的子页面。子页面已经知道这一点。如果您希望 dom-repeat 重新渲染,请尝试:this.slice('itemArray', itemArray);

标签: javascript polymer web-component polymer-1.0


【解决方案1】:

child-page 会在其 itemArray 属性更新时自动重新呈现其 template is="dom-repeat" items="[[itemArray]]"

只需将notify: true 添加到child-page 中的itemArray 属性即可启用与parent-page 元素的双向绑定。然后,每当child-pageitem-array 发生变化时,也会通知parent-page(参见Polymer documentation on this topic)。

这是一个完整的小例子:

<dom-module id="child-page">
  <template>
    <template is="dom-repeat" items="[[itemArray]]">
      <div>[[item]]</div>
    </template>
    <div on-click="_changeArray">Change</div>
  </template>
  <script>
    Polymer({
      is: 'child-page',
      properties: {
        itemArray: {type: Array, notify: true}
      },
      _changeArray: function() {
        this.itemArray = [4,5,6,7,8,9];
      }
    })
  </script>
</dom-module>

<dom-module id="parent-page">
  <template>
    <span>Item count: </span><span>[[itemArray.length]]</span>
    <child-page item-array="{{itemArray}}"></child-page>
  </template>
  <script>
    Polymer({
      is: 'parent-page',
      properties: {
        itemArray: {type: Array, value: [1,2,3]}
      }
    })
  </script>
</dom-module>

<parent-page></parent-page>

顺便说一句。注意我对{{...}}[[...]] 的使用。 Use curly braces for two-way bindings and square brackets for one-way bindings.

【讨论】:

  • 解释得很漂亮。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多