How to remove a child component with a delete button in the child itself

前端 未结 2 837
盖世英雄少女心
盖世英雄少女心 2020-12-12 00:31

I have an email component (email-tag.html) that consist of a label, a select and a delete button element.

The email-tag.html component is hosted in its parent email

相关标签:
2条回答
  • 2020-12-12 00:34

    The child component, <email-tag> should not be in the business of deleting itself. Instead, it should delegate that responsibility to the the parent component, email-view-tag, by dispatching a custom event.

    Here is the code for dispatching a custom event from deletePhone:

    void deletePhone( Event e, var detail, Node target){
      dispatchEvent(new CustomEvent('notneeded'));
    }
    

    Then, in the parent, <custom-view>, change your code for adding <email-tag>s like so:

    void addPhone( Event e, var detail, Node target ) {
      $['rows'].children.add( new Element.tag('email-tag'));
      $['rows'].on["notneeded"].listen((Event e) {
        (e.target as Element).remove();
      });
    }
    

    Also, I would change the name of deletePhone, since the method no longer deletes the record but merely informs the parent that it is not needed. Call it 'notNeeded' or something similar.

    0 讨论(0)
  • 2020-12-12 00:57

    EDIT @ShailenTuli is right about encapsulation should not be broken.

    But also JS Polymer elements access the parent in their layout elements because it's still convenient in some scenarios.

    This works now in PolymerDart too.

    (this.parentNode as ShadowRoot).host
    

    ORIGINAL

    You can fire an event and make the email-view-tag listen to this tag and the event handler can remove the event target from it's childs.

    • I had a similar question a while ago: How to access parent model from polymer component

    • This was actually the question I wanted refer to
      How can I access the host of a custom element
      but the first one may be of some use too.

    • PolymerJS FAQ - When is the best time to access an element’s parent node?
      attached() currently still named enteredView() in Dart, but will be renamed probably soon.

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