Often child components must notify parent ones that something happened: a button was pushed, a form was confirmed, etc. In Polymer, such notification can be implemented using the standard observer pattern. A child component sends some event and a parent listens to it.
Let’s consider the following example: there is a simple form consisting of an input and a button. Users enter their name and the form notifies the parent component that the form was confirmed and passes the entered name to the parent.
The form
Source code
<html>
<head>
<link rel="import" href="src/polymer-basic/events/event-manager.html">
<script src="bower_components/webcomponentsjs/webcomponents-loader.js"></script>
</head>
<body>
<event-manager></event-manager>
</body>
</html>
link:../../../../source/polymer-build/src/polymer-basic/events/event-manager.html[role=include]
link:../../../../source/polymer-build/src/polymer-basic/events/participation-form.html[role=include]
Tip
|
If you have some experience with JavaScript events, you probably noticed that we didn’t put For example, there are Component1, Component2 and Component3.
Component1 contains Component2.
Component2 contains Component3.
Component3 sends some event.
In this case Component2 will receive this event and Component1 won’t.
This behavior is convenient in most cases but can be changed by using |
- What we have learned so far
-
-
The
dispatchEvent(event)
method is used to send events. To create an event, we can useCustomEvent
constructor which accepts as parameters the event name (mandatory) and a settings object (optional). We can put our custom parameters into thedetail
property of the settings object. -
on-{eventName}
attributes are used to listen to events. -
Event parameters can be retrieved using the
detail
property of an event.
-