【问题标题】:Dynamically add a web component to a div将 Web 组件动态添加到 div
【发布时间】:2013-04-06 23:53:22
【问题描述】:

我从生成点击计数器示例开始。我将点击计数器制作成一个库,然后将其导入到我的主文件中。可以通过在运行程序之前将适当的 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);
}

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

【问题讨论】:

    标签: dart dart-webui


    【解决方案1】:

    我有同样的问题。 请参阅https://github.com/dart-lang/web-ui/blob/master/test/data/input/component_created_in_code_test.html 的示例(不是我的),如果它适合您,请告诉我。

    TL;DR:

    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

    希望对您有所帮助。

    【讨论】:

    • 嗨。这解决了我的问题。我打算将代码作为新答案发布,但我希望你能得到分数,所以也许你可以编辑你的,附加代码。然后我将其标记为答案。
    猜你喜欢
    • 2018-04-17
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多