2013-04-06 61 views
4

出於演示的原因,我創建了一個繼承自WebComponent的類FancyOption,該類更改爲單擊另一個子元素時由一個子元素中的文本指定的背景色。Dart Web組件如何獲取對其子項的引用?

import 'package:web_ui/web_ui.dart'; 
import 'dart:html'; 

class FancyOptionComponent extends WebComponent { 
    ButtonElement _button; 
    TextInputElement _textInput; 

    FancyOptionComponent() { 
    // obtain reference to button element 
    // obtain reference to text element 

    // failed attempt 
    //_button = this.query('.fancy-option-button'); 
    // error: Bad state: host element has not been set. (no idea) 

    // make the background color of this web component the specified color 
    final changeColorFunc = (e) => this.style.backgroundColor = _textInput.value; 
    _button.onClick.listen(changeColorFunc); 
    } 
} 

FancyOption HTML:

<!DOCTYPE html> 

<html> 
    <body> 
    <element name="x-fancy-option" constructor="FancyOptionComponent" extends="div"> 
     <template> 
     <div> 
      <button class='fancy-option-button'>Click me!</button> 
      <input class='fancy-option-text' type='text'> 
     </div> 
     </template> 
     <script type="application/dart" src="fancyoption.dart"></script> 
    </element> 
    </body> 
</html> 

我有他們三個這樣的頁面上。

<!DOCTYPE html> 

<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Sample app</title> 
    <link rel="stylesheet" href="myapp.css"> 
    <link rel="components" href="fancyoption.html"> 
    </head> 
    <body> 
    <h3>Type a color name into a fancy option textbox, push the button and 
    see what happens!</h3> 

    <div is="x-fancy-option" id="fancy-option1"></div> 
    <div is="x-fancy-option" id="fancy-option2"></div> 
    <div is="x-fancy-option" id="fancy-option3"></div> 

    <script type="application/dart" src="myapp.dart"></script> 
    <script src="packages/browser/dart.js"></script> 
    </body> 
</html> 

回答

6

只需使用getShadowRoot()和查詢反對:

import 'package:web_ui/web_ui.dart'; 
import 'dart:html'; 

class FancyOptionComponent extends WebComponent { 
    ButtonElement _button; 
    TextInputElement _textInput; 

    inserted() { 
    // obtain references 
    _button = getShadowRoot('x-fancy-option').query('.fancy-option-button'); 
    _textInput = getShadowRoot('x-fancy-option').query('.fancy-option-text'); 

    // make the background color of this web component the specified color 
    final changeColorFunc = (e) => this.style.backgroundColor = _textInput.value; 
    _button.onClick.listen(changeColorFunc); 
    } 
} 

哪裏x-fancy-option字符串是元素的名稱。

注意:我將您的構造函數更改爲inserted()方法,which is a life cycle method

+0

我試過了。它不會崩潰,但它現在不渲染組件。它給出了警告: 「_root」不是FancyOptionComponent的成員。 sdk版本0.4.4.4_r20810 – 2013-04-07 20:23:48

+1

哦,現在我知道爲什麼。你應該在'inserted()'中做你的邏輯,而不是在構造函數中。我會更新我的答案。 – 2013-04-07 22:07:20

+0

輝煌。這工作。有趣的是,_root仍然會產生該警告,但程序行爲是我想要的,所以我非常滿意。謝謝,凱。 – 2013-04-07 22:19:37

2

我明白_root是depracated。建議_root的答案應該使用getShadowRoot()來代替_root。

+0

優秀。感謝您的意見。 – 2013-05-15 15:13:30

+0

我更新了我的答案。 – 2013-07-25 11:48:39

相關問題