SSS
SSS

Reputation: 791

Dart: Extend HTMLElement with abstract class

I was trying to write something with the following design pattern:

void main() 
{
    document.registerElement('abs-test', Test);
    TestExtend test = new TestExtend();
    document.body.append(test);
}

abstract class Test extends HtmlElement
{
    Test.created() : super.created();
    factory Test() => new Element.tag('abs-test')..text = "test";
}

class RedTest extends Test
{
    TestExtend() : super() => style.color = 'red';  
}

My aim with this is to create a custom HtmlElement registered to the abstract class "Test". This abstract class "Test" would have some properties that all elements of type Test need to have. In this example, all elements of type Test need to have the word "test" as their text.

However, I wanted then to only allow the user to create subclasses of "Test" with more specific properties. In this example we have RedTest which then sets the color of Test to red. The resulting HTML would be:

<abs-test style="color:red;">test</abs-test>

I have 2 problems with this:

1) Is it possible to call the factory constructor of a parent class? (If not, is it possible to extend HtmlElement in a different way that doesn't require a factory constructor)

2) Is it possible to extends HtmlElement with an abstract class?

I have been testing for a while with different constructors but am unable to make it work. Can anyone advice?

Upvotes: 3

Views: 372

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657048

You register a tag with a class so that the browser can instantiate it for you. If this isn't an 1:1 relation, there is no way for the browser to know what class to instantiate.

Therefore

You need

  • a different tag for each class
  • register each tag with a concrete (non-abstract) class

You normally can call the constructor of a subclass in a factory constructor of an abstract class

factory Test() => new RedTest()..text = "test";

is valid in Dart, but because extending an element requires to return

new Element.tag('abs-test')

this won't work, because you can't return both at the same time.

You need to register each concrete subclass with a different tag like

document.registerElement('abs-test-red', TestRed);
document.registerElement('abs-test-blue', TestBlue);

Upvotes: 2

Related Questions