2014-06-07 74 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

相关问题