Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending dart:html classes in dart

Tags:

html

web

dart

I am new to Dart and I wonder if I can, for example, extend the DivElement class to create custom elements in one line of code. I am looking for something like this;

class RedBox extends DivElement {
    RedBox(text) {
        this.text = text;
        this.style.background = "red";
    }
}

RedBox myBox = new RedBox("Hello World");
document.body.append(myBox);

Of course I will have much more complex elements with custom functions. But just in general, is this possible?

When I try to run this, i get:

implicit call to super constructor 'DivElement()'
like image 844
Dafen Avatar asked Jan 11 '23 20:01

Dafen


2 Answers

You can extend HTML elements, but there are a few requirements. The one you're running into now is that you need a RedBox.created constructor, and it can only redirect to its super class. created must be the only generative constructor, though you can add factory constructors.

Another requirement is that the element is registered with document.registerElement.

Try adding this:

class RedBox extends HtmlElement {
  RedBox.created() : super.created() {
    style.background = "red";
  }
  factory RedBox(text) => new Element.tag('my-redbox')..text = text;
}

document.registerElement('my-redbox', RedBox);
like image 89
Justin Fagnani Avatar answered Jan 22 '23 17:01

Justin Fagnani


Some note on extending HtmlElement.
Example: https://api.dartlang.org/1.14.1/dart-html/HtmlDocument/registerElement.html
Pitfalls:

  1. Extending non HtmlElement(e.g. PreElement) throws:

HierarchyRequestError: Custom element XXX is a native PreElement should be derived from HtmlElement or SvgElement.

  1. Using extendsTag option with registerElement suppresses the above error but causes "new Element.tag('xxx')" to return an instance of HtmElement.

document.registerElement('xxx', XXX, extendsTag:'pre');

Solution(Assuming extending PreElement):
Use 'document.registerElement('xxx', XXX, extendsTag:'pre');' and 'new Element.tag('pre','xxx');'

void main{
  document.registerElement('xxx',
      XXX,extendsTag: 'pre');
      querySelectior('body').append(new XXX()..text = 'hello');
  }
  class XXX extends PreElement{
    XXX.created():super.created(){}
    factory XXX(){
      return new Element.tag('pre','xxx');
    }
  }

Dart does not currently support library initialization. You must call document.registerElement in the main.

Tested with 1.14.0

like image 24
3 revs Avatar answered Jan 22 '23 17:01

3 revs