Skip to content

Latest commit

 

History

History
77 lines (60 loc) · 2.57 KB

polymer_manual__basic__events.adoc

File metadata and controls

77 lines (60 loc) · 2.57 KB

Events Firing and Handling

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

index.html
<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>
src/polymer-basic/events/event-manager.html
link:../../../../source/polymer-build/src/polymer-basic/events/event-manager.html[role=include]
src/polymer-basic/events/participation-form.html
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 e.stopPropagation() expression into formSubmitted(e) method of the EventManager component. The reason we don’t stop propagation is that there is no propagation since CustomEvents by default do not cross shadow DOM boundaries.

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 composed property. See more details in the official guide.

What we have learned so far
  • The dispatchEvent(event) method is used to send events. To create an event, we can use CustomEvent constructor which accepts as parameters the event name (mandatory) and a settings object (optional). We can put our custom parameters into the detail 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.