我想要一个子元素派发一个自定义事件,并让父元素监听它,并采取一些措施。使用Polymer时我该怎么做?
最佳答案
您可以像这样从 polymer 元素调度自定义事件:
dispatchEvent(new CustomEvent('nameOfEvent'));
然后,父元素可以监听自定义事件,如下所示:
<child-element on-childspeaks="fireAway"></child-element>
这是一个更完整的示例,显示了它是如何工作的。首先,这是child元素的代码:
<!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>