我在dart lang上从头开始新项目,并且遇到了调用聚合物元素实例的问题。
例如,我有 fps-counter 元素( fpsCounter.dart ):
@HtmlImport('fps_counter.html')
library fpsCounter;
import 'package:web_components/web_components.dart' show HtmlImport;
import "package:polymer/polymer.dart";
import "dart:html";
@CustomTag("fps-counter")
class FpsCounter extends PolymerElement
{
@observable
int fps;
// counter that will cleared at 60 ticks
int _counter = 0;
// accumulator delta time for 60 ticks
int _accumulator = 0;
factory FpsCounter() => new Element.tag('fps-counter');
FpsCounter.created() : super.created() {
polymerCreated();
}
bool calculateFps(double delta)
{
if (_counter == 60)
{
fps = (60000 / _accumulator).round();
_counter = 0;
_accumulator = 0;
print("$fps FPS");
return true;
}
_accumulator += delta;
_counter++;
return false;
}
}
并希望从以下示例中调出calculateFps(0.016)
:
void _initRenderer(OSE ose)
{
FpsCounter fpsCounter = new FpsCounter();
fpsCounter.calculateFps(0.016);
document.body.children.add(fpsCounter);
}
但面临问题:
Exception: Uncaught Error: Class 'HtmlElement' has no instance method 'calculateFps'.
我真的不想围绕它创建额外的沟通,任何想法如何使其更好或如何调用方法?感谢。
pubspec.yaml
name: os
version: 0.0.1
dependencies:
browser: ">=0.10.0 <0.11.0"
ose:
path: ./libs/ose
polymer: any
transformers:
- polymer
FPS-counter.html
<link rel="import" href="packages/polymer/polymer.html" />
<polymer-element name="fps-counter">
<template>
<div>
{{fps}} FPS
</div>
</template>
<script type="application/dart" src="fpsCounter.dart"></script>
</polymer-element>
答案 0 :(得分:0)
这看起来像升级您的自定义元素失败,可能是由于缺少导入。否则FpsCounter fpsCounter = new FpsCounter();
会返回真实的FpsCounter
个实例,并且调用calculateFps(...)
会有效。
添加到fps_counter.dart
文件的顶部:
@HtmlImport('fps_counter.html')
library some_library;
import 'package:web_components/web_components.dart' show HtmlImport;
您需要将条目页面添加到pubspec.yaml
polymer
转换器部分
transformers:
- polymer:
entry_points:
- web/index.html
您需要导入包含类FpsCounter
的dart文件,否则您无法使用FpsCounter
作为类型注释或。
你需要保留FpsCounter.created() : super.created()
构造函数,如果不扩展DOM元素,就不要在其中调用polymerCreated()
。
我还必须更改您的main()
方法。初始化Polymer的方式仅适用于>=1.0.0-rc.x
,但使用any
时,您不会获得预发行版,但会获得0.16.3 + 3。另请参阅how to implement a main function in polymer apps
import 'os.dart';
import 'package:polymer/polymer.dart';
export 'package:polymer/init.dart';
@whenPolymerReady
init() async {
OS os = new OS();
os.start();
}
现在它正在运作