2014-06-07 75 views
1

在過去的幾個小時裏,我一直在努力參考我的聚合物項目中的兄弟元素。想象一下以下設置:請參考飛鏢中的同胞聚合物元素?

/* main.html */ 
<link rel="import" href="siblingA.html"> 
<link rel="import" href="siblingB.html"> 

<polymer-element name="app-main"> 
    <template> 
     <app-siblingA></app-siblingA> 
     <app-siblingB></app-siblingB> 
    </template> 
    <script type="application/dart" src="main.dart"></script> 
</polymer-element> 

/* siblingA.html, nothing special about it */ 
<polymer-element name="app-siblingA"> 
    <template> 
     <button on-click="{{doSomething))">Do something</button> 
    </template> 
    <script type="application/dart" src="siblingA.dart"></script> 
</polymer-element> 

/* siblingA.dart */ 
import 'package:polymer/polymer.dart'; 
import 'dart:html'; 

@CustomTag('app-siblingA') 
class SiblingA extends PolymerElement { 
    bool get applyAuthorStyles => true; 

    SiblingA.created() : super.created() { 
    } 

    void doSomething(MouseEvent e, var detail, Node target) { 
    var profile = document.querySelector('app-siblingB'); 
    print(profile); // This is always null, why? 
    } 
} 

現在我可以從文件讓我app-main節點,但它讓兄弟元素失敗。我試圖通過shadowRoot獲得兄弟元素,但沒有成功。

如何從documentshadowRoot獲取兄弟元素,在這種情況下爲app-siblingB

回答

2

你的兄弟姐妹在<app-main>的影子DOD內。 document.querySelector()沒有達到元素的影子DOM。

這應該工作

(parentNode as ShadowRoot).querySelector('app-siblingB'); 
+0

這是否解決方案仍然有效?我得到一個異常「打破異常:類型'DocumentFragment'不是在類型轉換類型'ShadowRoot'的子類型。」當投射到ShadowRoot – Wienczny

+1

我發現我的代碼不工作的原因:該元素沒有(尚未)連接到DOM。在調用void attach()之前,parentNode是一個DocumentFragment。我在'void ready()'中使用它。 – Wienczny

相關問題