在Dart中动态添加WebComponent?

时间:2013-06-09 04:34:43

标签: dart dart-webui

我试图按照此处的代码进行操作:

component_created_in_code_test.html

component_created_in_code.dart

但是,当我获得依赖项并在dartium中运行代码时,我收到以下错误。调用ComponentItem的create()方法(在.dart代码中)时会发生此错误:

Breaking on exception: Class 'SayHello' has no instance method 'created_autogenerated'.

我在下面稍微重写了一下(代码是相同的,除了main已被移动为dart代码而不是内联):

<!-- component_created_in_code_test.html -->
<!doctype html>
<!--
Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
for details. All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
-->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <script src="packages/web_ui/testing/testing.js"></script>
</head>
<body>
  <element name="say-hello">
    <template>Hello {{name}}!</template>
    <script type='application/dart' src="component_created_in_code.dart">
    </script>
  </element>
  <say-hello name="component create in html"></say-hello>
</body>
</html>

以及以下飞镖码,

//component_created_in_code.dart

library component_created_in_code;

import 'dart:async';
import 'dart:html';
import 'package:web_ui/web_ui.dart';

class SayHello extends WebComponent {
  String name;
}

void main() {
  Timer.run(() {
    var hello = new SayHello()
    ..host = new DivElement()
    ..name = 'component created in code';

    // "hello" is the DOM node.
    // "hello.xtag" is your SayHello object.
    // We are working on making these be the same object.

    // If the component uses data-binding, we need to make sure the
    // "lifecycle" methods get called. We are working to make this be
    // automatic too.
    var lifecycleCaller = new ComponentItem(hello)..create();
    document.body.nodes.add(hello.host);
    lifecycleCaller.insert();
    window.postMessage('done', '*');
  });
}

看来这个dart-lang示例存在问题。我错过了什么,或者代码刚刚被剔除了?


在回答了这个问题之后,我打包了问题的工作解决方案。

component_created_in_code

只需从git中提取,然后导入dartEditor。然后从编辑器中“pub install”和“重新分析源”(永不伤害),然后在“web / component_created_in_code.html”上右键单击“Run in Dartium”。

2 个答案:

答案 0 :(得分:1)

我使用build 0.5.13_r23552编辑器测试了相同的内容。 SDK在Dartium中运行时会遇到同样的问题。如果我执行dart2js(以Javascript运行/生成javascript),它可以工作。

但是,请注意以下事项(根据我的经验):

  • 尝试更改为已经过测试和验证的SDK版本。
  • 似乎测试更新为以0.5.15运行;与dartlang网站上的编辑器一起提供的SDK仅为0.5.13。也许克隆前沿版本才能使其有效?
  • Dart不断进化。如果您使用的是依赖项而不是特定的库版本,请在更新到最新编辑器后对项目进行pub更新。
  • 将build.dart添加到项目中,以确保在更改时生成代码(请参阅本页底部:Build.dart setup

答案 1 :(得分:1)

听起来您需要先运行Web UI编译器。在HTML文件上运行packages / web_ui / dwc.dart,或者沿着这些行编写build.dart:

import 'dart:io';
import 'package:web_ui/component_build.dart';

void main() {
  build(new Options().arguments, ['web/component_created_in_code_test.html']);
}