Handling User Events in a PolymerTemplate

Client Side Event Handlers

PolymerTemplate defines a special syntax on-*event*="methodName" for attaching client side event handlers to elements. (Note! that the method should be without any arguments and have no parenthesis)

To wire an event to a Polymer.Element method you can write a template as:

HTML

  1. <dom-module id="x-custom">
  2. <template>
  3. <button on-click="handleClick">Say hello</button>
  4. </template>
  5. <script>
  6. class XCustom extends Polymer.Element {
  7. static get is() {return 'x-custom'}
  8. handleClick() {
  9. console.log('Button was clicked.');
  10. window.alert('Hello');
  11. }
  12. }
  13. customElements.define(XCustom.is, XCustom);
  14. </script>
  15. </dom-module>

Clicking on the <button> will now show an alert in the browser. You can listen to any event using the on-*event* syntax, it does not matter if it is a built-in browser event or a custom event from e.g. a web component.

Server-Side Event Handlers

To handle a DOM event in a template on the server side you can create a method with the event name and annotate it with @EventHandler.

So to listen to the handleClick event on the server you could have the template as:

HTML

  1. <dom-module id="event-handler">
  2. <template>
  3. <button on-click="handleClick">Click me</button>
  4. </template>
  5. <script>
  6. class EventHandler extends Polymer.Element {
  7. static get is() { return 'event-handler' }
  8. }
  9. customElements.define(EventHandler.is, EventHandler);
  10. </script>
  11. </dom-module>

And define the server class as:

Java

  1. @Tag("event-handler")
  2. @HtmlImport("/com/example/EventHandler.html")
  3. public class EventHandlerPolymerTemplate extends PolymerTemplate<TemplateModel> {
  4. @EventHandler
  5. private void handleClick() {
  6. System.out.println("Received a handle click event");
  7. }
  8. }

The framework will wire up the client-side event when having the @EventHandler annotation on the method handleClick().

Note
If a case arises where there is a client-side implementation of the server event handler the client side method will be executed before the server-side event handler method is called.

Adding Event Data to server-side event

An event can also include additional information about what has happened, e.g. which mouse button was used for a click event. When you use @EventHandler annotation, all constructor parameters should have an @EventData annotation that tells the framework what data to send from the browser.

HTML

  1. <!-- same template as for the server-side event handler -->
  2. <template>
  3. <button on-click="handleClick">Click me</button>
  4. </template>

To get some extra data on event type and element tag name the server class definition could be built like:

Java

  1. @Tag("event-handler")
  2. @HtmlImport("/com/example/EventHandler.html")
  3. public class EventDataHandlerPolymerTemplate extends PolymerTemplate<TemplateModel> {
  4. @EventHandler
  5. private void handleClick(@EventData("event.altKey") boolean altPressed,
  6. @EventData("event.srcElement.tagName") String tag,
  7. @EventData("event.offsetX") int offsetX,
  8. @EventData("event.offsetY") int offsetY) {
  9. System.out.println("Event alt pressed: " + altPressed);
  10. System.out.println("Event tag: " + tag.toLowerCase(Locale.ENGLISH));
  11. System.out.println("Click position on element: [" + offsetX + ", "+ offsetY +"]");
  12. }
  13. }

Now the client would send the extra information back to the server for event.type, event.srcElement.tagName and the event.offset[X/Y] can then be used like normal variables.

Note
The server will throw an exception if the EventData can not be converted to given format. for instance you could get the exception java.lang.ClassCastException: Cannot cast elemental.json.impl.JreJsonNumber to elemental.json.JsonObject Also the client might throw exceptions if the value given for EventData can not be executed or converted to Json.

There is a shorthand for getting model specific item as an object in your event handler. To be able to use it you should define your model (see Using Beans with a PolymerTemplate Model) in the template class.

Java

  1. @Tag("model-item-handler")
  2. @HtmlImport("/com/example/ModelItemHandler.html")
  3. public class ModelItemHandlerPolymerTemplate
  4. extends PolymerTemplate<MessagesModel> {
  5. public static class Message {
  6. private String text;
  7. public Message() {
  8. }
  9. public Message(String text) {
  10. this.text = text;
  11. }
  12. public String getText() {
  13. return text;
  14. }
  15. public void setText(String text) {
  16. this.text = text;
  17. }
  18. }
  19. public interface MessagesModel extends TemplateModel {
  20. void setMessages(List<Message> messages);
  21. }
  22. @EventHandler
  23. private void handleClick(@ModelItem Message message) {
  24. System.out.println("Received a message: " + message.getText());
  25. }
  26. }

Now you can use the template repeater (dom-repeat) (see Using List of Items in a PolymerTemplate with template repeater) and handle click events on the server side with Message as the parameter type.

HTML

  1. <dom-module id="model-item-handler">
  2. <template>
  3. <dom-repeat items="[[messages]]">
  4. <template><div class='msg' on-click="handleClick">[[item.text]]</div></template>
  5. </dom-repeat>
  6. </template>
  7. <script>
  8. class ModelItemHandler extends Polymer.Element {
  9. static get is() { return 'model-item-handler' }
  10. }
  11. customElements.define(ModelItemHandler.is, ModelItemHandler);
  12. </script>
  13. </dom-module>

The method handleClick will be called in the server side with the data identified by event.model.item once the item is clicked.

Note
You can use the annotation @ModelItem with any value provided as a data path. By default the data path is event.model.item. But your data type should be declared somehow via the model definition (it should be referenced from the model).
Note
Please note that @ModelItem is just a convenience way of model data access. The argument which you receive in your event handler callback is the model data from the server side which you may access directly via your model instance. It means that the server doesn’t update the model item anyhow from the client. So if you create a custom event on the client side with data that you want to send to the server as a model item it will be completely ignored by the server-side and the current model data will be used instead. You always should keep your model in sync on the server and client-sides, by correctly updating it.

So if you have the following model definition and the event handler method:

Java

  1. public static class UserInfo {
  2. private String name;
  3. public String getName() {
  4. return name;
  5. }
  6. public void setName(String name) {
  7. this.name = name;
  8. }
  9. }
  10. public interface Model extends TemplateModel {
  11. void setUserInfo(UserInfo userInfo);
  12. }
  13. @EventHandler
  14. private void onClick(
  15. @ModelItem("event.detail.userInfo") UserInfo userInfo) {
  16. System.err.println("contact : name = " + userInfo.getName());
  17. }

Then the client side code below won’t update the name of the UserInfo bean instance.

HTML

  1. <dom-module id="contact-handler">
  2. <template>
  3. <input id="name" type="text">
  4. <button on-click="onClick">Send the contact</button>
  5. </template>
  6. </dom-module>
  7. <script>
  8. class ContactHandler extends Polymer.Element {
  9. static get is() { return 'contact-handler' }
  10. onClick(event) {
  11. this.userInfo.name = this.$.name.value;
  12. event.detail = {
  13. userInfo: this.userInfo,
  14. };
  15. }
  16. customElements.define(ContactHandler.is, ContactHandler);
  17. </script>
  18. }

In this example the server-side model becomes desynchronized with the client side because client side model is updated incorrectly. The line this.userInfo.name = this.$.name.value should be replaced to this.set("userInfo.name", this.$.name.value). That’s the correct way to update sub-properties in Polymer. But in this case the server-side model will be updated automatically for you and there is no need to send this custom event at all. You may just notify somehow the server about the click event (e.g. via this.$server and a @ClientCallable method, see Creating A Simple Component Using the Template API) and get the model value directly from the server-side model.