passing parameter/input data to custom elements in DART

流过昼夜 提交于 2019-12-02 04:39:34
Günter Zöchbauer

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%';

This is another solution that worked with me before reading the posted answers, I liked @Gunter answer and will adapt it.

class SaveBtn extends HtmlElement  {
  static final tag = 'save-button';
  factory SaveBtn()=>new Element.tag(tag);

  var shadow, btn;

  SaveBtn.created() : super.created() {
    shadow = this.createShadowRoot();

    btn = new ButtonElement()
        ..text="save"
        ..style.height= '20px'  
        ..style.borderBottom='1px solid #D1DBE9'; 

    btn.text = this.getAttribute('data-name');

    shadow.nodes..add(label)..add(btn);
  } 

  Element launchElement(name){ 
    btn.text= name;
    return (shadow); 
  }
}

and called the element as:

var btn=new SaveBtn()..launchElement('click me');

You can simply add a new constructor for this that sets the data-name attribute too:

class SaveBtn {
  // ...
  factory SaveBtn(String label) {
    var btn = new Element.tag(tag);
    btn.setAttribute('data-name', label); // Set properties/call methods here
    return btn;
  }
  // ...
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!