我正在尝试创建一个扩展paper-shadow
的自定义Polymer元素来显示推文。
这是我的实施:
tweet_element.html
<link rel="import" href="packages/paper_elements/paper_shadow.html">
<link rel="import" href="packages/polymer/polymer.html">
<link rel="stylesheet" href="tweet_element.css">
<polymer-element name="tweet-element" extends="paper-shadow">
<template>
<div id="header">
<div id="user-image">
<img src="{{userImageUrl}}">
</div>
<div id="details">
<div id="user">{{user}}</div>
<div id="date-published">{{datePublished}}</div>
</div>
</div>
<div id="content">
<div id="text">{{text}}</div>
<div id="photos">{{photos}}</div>
</div>
</template>
<script type="application/dart" src="twitter.dart"></script>
</polymer-element>
twitter.dart
import 'package:polymer/polymer.dart';
@CustomTag('tweet-element')
class TweetElement extends PolymerElement {
@Observable String userImageUrl;
@Observable String user;
@Observable String datePublished;
@Observable String text;
TweetElement.created() : super.created();
void update(Tweet tweet) {
userImageUrl = tweet.user.profileImage;
user = '${tweet.user.name} (@${tweet.user.screenName})';
datePublished = _parseDate(tweet.date);
text = tweet.text;
}
...
}
最后创建TweetElement并尝试将其添加到DOM的代码:
import 'dart:html';
import 'package:polymer/polymer.dart';
import 'twitter.dart';
...
var mainContent = querySelector('#main-content');
var element;
for (var tweet in tweets) {
element = new TweetElement.created();
element.update(tweet);
mainContent.children.add(element);
}
当我跑步时,我得到:
Exception: Uncaught Error: created called outside of custom element creation.
然后我尝试将 twitter.dart 更改为:
TweetElement.created() : super.created();
TweetElement (Tweet tweet) {
TweetElement.created();
userImageUrl = tweet.user.profileImage;
user = '${tweet.user.name} (@${tweet.user.screenName})';
datePublished = _parseDate(tweet.date);
text = tweet.text;
}
并将元素添加到DOM中:
var mainContent = querySelector('#main-content');
var element;
for (var tweet in tweets) {
element = new TweetElement(tweet);
mainContent.children.add(element);
}
现在我收到了这个错误:
Internal error: unresolved implicit call to super constructor 'PolymerElement()' TweetElement (Tweet tweet) {
答案 0 :(得分:1)
拉尔夫。
您可以通过两种方式实现这一目标:
选项A
如果要在Dart代码中创建Polymer Element,只需以这种方式创建该标记:
var myTweetElement = new Element.tag ('tweet-element');
mainContent.childern.add(myTweetElement);
另外,检查您是否导入了html库:
import 'dart:html';
选项B :(最酷的)
通过将此工厂添加到 twitter.dart ,您可以更方便(更面向对象):
factory TweetElement () => new Element.tag('tweet-element');
然后,在你的dart代码中创建标签更具可读性:
var myTweetElement = new TweetElement (); // This uses the factory transparently
mainContent.children.add(myTweetElement);
此外,您可以设置属性的值。由于这些是可观察的,绑定将自动更新:
myTweetElement.userImageUrl = "foo"
myTweetElement.user = "bar"
myTweetElement.datePublished = "baz"
myTweetElement.text = "qux"
或者,如果您喜欢级联运算符,则可以改为编写:
myTweetElement..userImageUrl = "foo"
..user = "bar"
..datePublished = "baz"
..text = "qux";
希望这会有所帮助。