Add listener to custom element in DART lang

Issue

In JavaScript, we can add listener to the custom element as mentioned here by:

proto.createdCallback = function() {
   this.addEventListener('click', function(e) {
   alert('Thanks!');
  });
};

I tried making equivalent DART code as:

    Element launchElement(){
       this.onClick.listen((e)=>print('Thanks!'));
       return (shadow);  
    }

Am I doing something wrong here?

the full code of my custom element is:

class MegaButton extends ButtonElement  {
  static final tag = 'mega-button';
  factory MegaButton()=>new Element.tag('button', tag);

MegaButton.created() : super.created() {
  var shadow = this.createShadowRoot();
  shadow.text='save'; 

  Element launchElement(){
    this.onClick.listen((e)=>print('Thanks!'));
    return (shadow);  
  }

}

registered it as:

document.registerElement(MegaButton.tag, MegaButton, extendsTag: 'button');

and called it by:

myDiv.nodes.add(new Element.tag('button', 'mega-button'));

Solution

class MegaButton extends ButtonElement {
  static final tag = 'mega-button';

  factory MegaButton()=> new Element.tag('button', tag);

  MegaButton.created() : super.created() {
    var shadow = this.createShadowRoot();
    shadow.text = 'save';
  }

  void attached() {
    this.onClick.listen((e)=>print('Thanks!'));
  }
}

Answered By – Günter Zöchbauer

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *