首页 文章

聚合物1:父组件没有从子组件中监听fire事件's ' detached'方法?

提问于
浏览
1

我有一个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 回答

  • 0

    detached 事件无法按预期方式工作 .

    来自documentation

    detached元素从文档中分离后调用 . 可以在元素的生命周期内多次调用 . 用途包括删除附加中添加的事件侦听器 . 使用而不是detachedCallback .

    在元素与DOM树分离后调用 detached 回调,这意味着事件无法传播到它的父元素,因为它没有元素 .

    您将需要创建一个不同的机制,该机制不涉及在 detached 回调中触发事件 .

    例如,你可以在 child (你可以在 attached 回调中获得)中保存 parent 元素的引用,然后在 childdetached 事件处理程序中手动调用 parentonChildDetached 方法 .

  • 0

    解决方案:只要子组件的“附加”方法触发“EVT_CHILD_ATTACHED”并让父组件中的事件侦听器如此触发,就让ParentComponent将分离的方法添加到所有childComponent .

    Polymer({
        is: 'parent-component',
        listeners: { 
           'EVT_CHILD_ATTACHED': 'onChildAttached'
        },
        onChildAttached: function (evt) {
            console.log('child elem is ATTACHED');
            var self = this;
            evt.target.detached = function () {
                self.onChildDetached(this);
            }
        },
        onChildDetached: function (target) {
            console.log('child elem is DETACHED', target);
        }
    })
    

    可能不是最好的方式,但仍然可以做到这一点 .

相关问题