2013-04-14 83 views
2

我从生成的点击计数器示例开始。我将点击计数器放入一个库中,然后将其导入到我的主文件中。点击计数器组件可以通过在运行程序之前将适当的HTML放入网页来手动添加。但是,我一直无法找到一种方法来动态地将点击计数器Web组件添加到div。我的尝试要么以“噢,快点!”结束错误或根本没有发生任何事情。动态添加网络组件到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); 
} 

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

回答

2

我有同样的问题。 请参阅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(); 
} 

有我[email protected]邮政的更多信息:https://groups.google.com/a/dartlang.org/d/topic/web-ui/hACXh69UqG4/discussion

希望有所帮助。

+0

嗨。这解决了我的问题。我将发布代码作为新的答案,但我希望你能够获得积分,所以也许你可以编辑你的代码,附加代码。然后,我会将其标记为答案。 –

+0

格式化的代码:http://pastebin.com/2pV6v8DQ –