我有一个parentComponent和几个childComponents,如下所示:
<parent-component>
<child-component> child_1 </child-component>
<child-component> child_2 </child-component>
</parent-component>
为父级:
Polymer({
is: 'parent-component',
listeners: {
'EVT_CHILD_ATTACHED': 'onChildAttached'
'EVT_CHILD_DETACHED': 'onChildDetached'
},
onChildAttached: function () {
console.log('child elem is ATTACHED');
},
onChildDetached: function () {
console.log('child elem is DETACHED');
}
})
ChildComponent:
Polymer({
is: 'child-component',
attached: function () {
this.fire('EVT_CHILD_ATTACHED');
},
detached: function () {
this.fire('EVT_CHILD_DETACHED');
}
});
Success :将"new"子组件添加到父组件中时,子组件' method is called and the event '附加' method is called and the event ' EVT_CHILD_ATTACHED ' is fired and finally the parent-component is able to listen and log '子元素已成功附加 .
Failure :当删除了一个"existing"子组件时,我可以看到子组件's polymer lifecycle '分离' method is called and the event ' EVT_CHILD_DETACHED ' is fired as well. But the parent-component' s onChildDetached()从未被触发,也没有显示日志 .
Qn :当任何子组件为' detached '时,如何让父组件做出反应/监听?
注意:子组件可以动态添加或包装在循环条件或dom-if条件下,为了简单起见,我已经删除了这样的逻辑 .
2 回答
detached
事件无法按预期方式工作 .来自documentation:
在元素与DOM树分离后调用
detached
回调,这意味着事件无法传播到它的父元素,因为它没有元素 .您将需要创建一个不同的机制,该机制不涉及在
detached
回调中触发事件 .例如,你可以在
child
(你可以在attached
回调中获得)中保存parent
元素的引用,然后在child
的detached
事件处理程序中手动调用parent
的onChildDetached
方法 .解决方案:只要子组件的“附加”方法触发“EVT_CHILD_ATTACHED”并让父组件中的事件侦听器如此触发,就让ParentComponent将分离的方法添加到所有childComponent .
可能不是最好的方式,但仍然可以做到这一点 .