gpt4 book ai didi

dart - 如何从外部调用 polymer 元素实例的方法?

转载 作者:行者123 更新时间:2023-12-03 03:06:14 26 4
gpt4 key购买 nike

我在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>

最佳答案

这似乎是由于缺少导入而导致升级自定义元素失败。否则,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();
}

现在可以了

关于dart - 如何从外部调用 polymer 元素实例的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33501850/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com