passing parameter/input data to custom elements in DART

后端 未结 3 856
天命终不由人
天命终不由人 2021-01-24 16:28

I created a custom element, and want to send data / parameters to it:

my element code is:

   class SaveBtn         


        
3条回答
  •  旧巷少年郎
    2021-01-24 16:52

    name is an optional argument. When you pass a value it is used for the text attribute of the button.
    I pass it just to a field (name) in the elements class and set it to the the button in attached.
    When you use data-xxx attributes you can use the dataset getter.
    I also changed the other code a bit. I think attached is a better place to access attributes because then the element is already upgraded properly.

    class SaveBtn extends HtmlElement {
      static final tag = 'save-button';
    
      factory SaveBtn([String name]) => (new Element.tag(tag) as SaveBtn)..name = name;
    
      ButtonElement innerButton;
      ShadowRoot shadow;
    
      SaveBtn.created() : super.created() {
        //  Create a Shadow Root
        var shadow = this.createShadowRoot();
        // Create a standard element and set it's attributes.
        innerButton = new ButtonElement();
        shadow.nodes.add(innerButton);
      }
    
      String name;
    
      @override
      void attached() {
        super.attached();
        innerButton.text = name != null ? name : this.dataset['name'];
      }
    }
    
    SaveBtn({String name, String width}) => (new Element.tag(tag) as SaveBtn)
        ..name = name
        ..style.width=width;
    

    Below a solution proved to work.

    factory SaveBtn() => new Element.tag(tag)
      String name, width;
    
      @override
      void attached() {
        super.attached();
        innerButton.text = name != null ? name : this.dataset['name']
        ..style.width=width;
      }
    

    call the item as:

    var btn = new SaveBtn()..name='save'..width='100%';
    

提交回复
热议问题