2013-04-14 154 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 –