2013-05-02 43 views
1

如果我添加了一些Web組件,以我的應用程序,如下面myapp.html:Dart Web UI:如何獲取對Web組件中項目的引用?

<head> 
    <link rel="components" href="package:xclickcounter/xclickcounter.html"> 
</head> 
<body> 
    <div id="container1"><x-click-counter></x-click-counter></div> 
    <div id="container2"><x-click-counter></x-click-counter></div> 
    <div id="container3"><x-click-counter></x-click-counter></div> 
    <div id="container4"><x-click-counter></x-click-counter></div> 
    ... 
</body> 

而且我在我的web組件元素的數目如下xclick-counter.html:

<html><body> 
    <element name="x-click-counter" constructor="CounterComponent" extends="div"> 
    <template> 
     <button id="button1" on-click="increment()">\\\Increment me</button> 
     <button id="button2" on-click="decrement()">Decrement me</button> 
     <span>(click count: {{count}})</span> 
    </template> 
    </element> 
<!-- more below... --> 
</body></html> 

如何從myApp.dart中獲取#container3中Web組件中#button2的引用?

我希望我可以得到一個參考如下但是我參照原來是空:

var reference=document.query('#container1').query('#button2'); 

回答

2

一般情況下,你不應該試圖這樣做。 :) Shadow DOM是一個封裝邊界,自定義元素的模板內容應作爲實現細節隱藏。想想像一個類的自定義元素。您不想進入某個類並查看私有字段,就像您不想訪問自定義元素並查看Shadow DOM內的節點一樣。

說到這裏,我想提一個建議:在頁面上唯一

的Web UI目前不保持的ID(從內自定義元素)。對於x-click-counter的每個實例,頁面將具有重複的button1和button2元素。

我打開https://github.com/dart-lang/web-ui/issues/492來跟蹤問題。

解決方法是使用類而不是ID。然後,您可以爲主機元素提供一個ID,就像您在代碼中一樣。嘗試更改爲:

<element name="x-click-counter" constructor="CounterComponent" extends="div"> 
    <template> 
     <button class="button1" on-click="increment()">\\\Increment me</button> 
     <button class="button2" on-click="decrement()">Decrement me</button> 
     <span>(click count: {{count}})</span> 
    </template> 
    </element> 
+0

感謝您的好評。我建議的類解決方法似乎不工作作爲我的代碼「reference = document.query('#container1')。query('。button2');'仍然顯示爲空。我想底線是,我不在尋找我的Web組件被完全封裝,我需要相當於公共字段和私有字段。 – 2013-05-03 17:09:32

+0

您可能會閱讀更多關於Shadow DOM:http ://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/它可能會提供更多的上下文 – 2013-05-04 03:54:05

+0

感謝您的教程鏈接,這已經解釋了很多,我更新了我的代碼以消除訪問封裝元素的需要 – 2013-05-13 18:36:27

相關問題