Instantiating polymer element via dart code

2019-01-20 13:29发布

问题:

I'm trying to instantiate a Polymer element in my Dart code.

Here's my element:

@CustomTag('card-component')
class CardComponent extends PolymerElement {
  @published
  String playerName;

  CardComponent.created() : super.created();
}

So far the only way I found to be working was:

Element y = new Element.tag('card-component');

But what I would really like to do, would be to access the values of my component by their accessors (instead of by attributes of HtmlElement). Is there a way to instantiate a CardComponent directly in Dart without using the Element.tag way? I tried using the CardComponent.created() method in multiple ways but it didn't work either.

In case you wonder why I want to do this, well I would like to pass parameters to my constructor, or even use a factory to create the component in an ideal world.

Edit: After reading this answer I ended up being able to do what I wanted. I just had to had this to my component

factory CardComponent(String playerName) => document.createElement("card-component")
  ..attributes = {
    "playerName" : playerName
};

And then instantiate it like this:

CardComponent myNewCard = new CardComponent("Pacane");

回答1:

I don't know what exactly you mean by "to access the values of my component by their accessors (instead of by attributes of HtmlElement)"

(new Element.tag('card-component') as CardComponent)
    ..playerName = 'blabla';

adding a custom factory constructor allows you to use the element as if it had a normal constructor

@CustomTag('card-component')
class CardComponent extends PolymerElement {
  @published
  String playerName;

  CardComponent.created() : super.created();

  factory CardComponent CardComponent() {
    return new Element.tag('card-component');
  }
}
var cc = new CardComponent()..playerName = 'blabla';

If you want to do this from main() not from within another component, ensure that main() contains the Polymer (initialization code why am I getting type error on polymer.dart element?, how to implement a main function in polymer apps)