How to get a callback when a custom element *and it's children* have been initialized

前端 未结 1 1002
[愿得一人]
[愿得一人] 2021-01-05 14:06

I\'m nesting custom elements. I\'d like to have my parent custom element use methods and properties from its child custom element\'s prototype. E.g.



        
1条回答
  •  礼貌的吻别
    2021-01-05 14:52

    Actually, there are many different ways to achieve this with nested custom elements.

    The direct way is to add a custom callback to the parent element that will be called by the child element from its attachedCallback method:

    ParentElement.childAttachedCallback = function ()
    {
        console.log( this.childNodes[0].getName() )
    }
    
    ChildElement.attachedCallback = function()
    {
        this.parentElement.childAttachedCallback()
    }
    

    In a complex scenario you could use instead:

    • a Promise object set by the parent and resolve by one or more childs,
    • Custom Events fired by childs and caught by the parent,
    • a MutationObserver object set to observe changes in the parent's child list...

    0 讨论(0)
提交回复
热议问题