2013-09-26 50 views
11

我想要一個子元素來派發自定義事件和父元素來偵聽它,並採取一些行動。使用聚合物時我該怎麼做?你如何派遣和聽聚合物中的自定義事件?

+0

可能重複我怎麼火從聚合物飛鏢自定義事件?](http://stackoverflow.com/questions/18971511/how-do-i-fire-a-custom-event-from-polymer-dart) –

回答

14

可以從聚合物元素分派自定義事件是這樣的:

dispatchEvent(new CustomEvent('nameOfEvent')); 

然後,父元素可以監聽像這樣的自定義事件:

<child-element on-childspeaks="fireAway"></child-element> 

這裏是一個更完整顯示這是如何工作的示例。首先,這裏是子元素的代碼:

<!DOCTYPE html> 

<polymer-element name="child-element"> 
    <template> 
    <div on-click="dispatch">I am a child</div> 
    </template> 
    <script type="application/dart"> 
    import 'dart:html'; 
    import 'package:polymer/polymer.dart'; 

    @CustomTag('child-element') 
    class ChildElement extends PolymerElement with ObservableMixin { 

     dispatch(Event e, var detail, Node sender) { 
     print('dispatching from child'); 
     dispatchEvent(new CustomEvent('childspeaks')); 
     } 
    } 
    </script> 
</polymer-element> 

這裏是父元素的代碼:

<!DOCTYPE html> 
<link rel="import" href="child_element.html"> 
<polymer-element name="parent-element"> 
    <template> 
    <div>I am the parent</div> 
    <child-element on-childspeaks="fireAway"></child-element> 
    </template> 
    <script type="application/dart"> 
    import 'dart:html'; 
    import 'package:polymer/polymer.dart'; 

    @CustomTag('parent-element') 
    class ParentElement extends PolymerElement with ObservableMixin { 

     void fireAway() { 
     window.alert('The child spoke, I hear'); 
     } 
    } 
    </script> 
</polymer-element> 
的[
+0

是否需要使用ObservableMixin部分? –