我希望子元素调度自定义事件,父元素监听它,并采取一些操作。使用Polymer时该怎么做?
答案 0 :(得分:14)
您可以从聚合物元素中调度自定义事件,如下所示:
dispatchEvent(new CustomEvent('nameOfEvent'));
然后,parent元素可以像这样监听自定义事件:
<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>