3

我从生成点击计数器示例开始。我将点击计数器制作成一个库,然后将其导入到我的主文件中。可以通过在运行程序之前将适当的 HTML 放入网页中手动添加点击计数器组件。但是,我一直无法找到将点击计数器 Web 组件动态添加到 div 的方法。我的尝试要么以“噢,啪!”而告终。错误或根本没有发生任何事情。

点击计数器(xclickcounter.dart):

library clickcounter;
import 'package:web_ui/web_ui.dart';

class CounterComponent extends WebComponent {
  int count = 0;

  void increment() {
    count++;
  }
}

主要的 HTML:

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <title>Sample app</title>
    <link rel="stylesheet" href="test1.css">

    <!-- import the click-counter -->
    <link rel="components" href="xclickcounter.html">
  </head>
  <body>
    <h1>Test1</h1>

    <p>Hello world from Dart!</p>

    <div id="sample_container_id">
      <div is="x-click-counter" id="click_counter" count="{{startingCount}}"></div>
    </div>

    <script type="application/dart" src="test1.dart"></script>
    <script src="packages/browser/dart.js"></script>
  </body>
</html>

主文件:

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

// initial value for click-counter
int startingCount = 5;

void main() {
  // no error for adding an empty button
  var button = new ButtonElement();
  query('#sample_container_id').append(button);

  // doesn't work (gives "Aw, snap!" in Dartium)
  query('#sample_container_id').append(new CounterComponent());

  // Nothing happens with this code. Nothing appears.
  // But I promise this same thing was giving Aw, Snap 
  // for a very similar program
  final newComponentHtml = '<div is="x-click-counter"></div>';
  query('#sample_container_id').appendHtml(newComponentHtml);
}

我尝试向点击计数器添加一个空的构造函数,但它仍然崩溃。

4

1 回答 1

2

我遇到过同样的问题。请参阅https://github.com/dart-lang/web-ui/blob/master/test/data/input/component_created_in_code_test.html上的示例(不是我的),让我知道它是否适合您。

TL;博士:

void main() {
  var element = query('#sample_container_id');
  appendComponentToElement(element, new CounterComponent() );
}

void appendComponentToElement(Element element, WebComponent component) {
  component.host = new DivElement();
  var lifecycleCaller = new ComponentItem(component)..create();
  element.append(component.host);
  lifecycleCaller.insert();
}

在我的 web-ui@dartlang.org 帖子中有更多信息:https ://groups.google.com/a/dartlang.org/d/topic/web-ui/hACXh69UqG4/discussion

希望有帮助。

于 2013-04-17T19:34:47.033 回答