【问题标题】:Instantiating polymer element via dart code通过飞镖代码实例化聚合物元素
【发布时间】:2014-12-08 01:43:42
【问题描述】:

我正在尝试在我的 Dart 代码中实例化 Polymer 元素。

这是我的元素:

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

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

到目前为止,我发现工作的唯一方法是:

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

但我真正想做的是通过它们的访问器访问我的组件的值(而不是通过HtmlElement 的属性)。有没有办法直接在 Dart 中实例化 CardComponent 而无需使用 Element.tag 方式?我尝试了多种方式使用CardComponent.created() 方法,但也没有用。

如果您想知道我为什么要这样做,那么我想将参数传递给我的构造函数,或者甚至使用工厂在理想世界中创建组件。

编辑:阅读this answer 后,我最终能够做我想做的事。我只需要将它添加到我的组件中

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

然后像这样实例化它:

CardComponent myNewCard = new CardComponent("Pacane");

【问题讨论】:

标签: dart dart-polymer


【解决方案1】:

我不知道您所说的“通过其访问器访问我的组件的值(而不是通过 HtmlElement 的属性)”的确切含义

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

添加自定义工厂构造函数允许您像使用普通构造函数一样使用元素

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

如果您想从 main() 而不是从另一个组件中执行此操作,请确保 main() 包含 Polymer(初始化代码 why am I getting type error on polymer.dart element?how to implement a main function in polymer apps

【讨论】:

  • 感谢as CardComponent 的技巧!但工厂是真的想要我想要的。 :)
猜你喜欢
  • 1970-01-01
  • 2014-07-28
  • 2015-06-17
  • 2015-03-23
  • 1970-01-01
  • 2013-08-24
  • 1970-01-01
  • 1970-01-01
  • 2014-10-05
相关资源
最近更新 更多