Custom Event

I’m trying to fire a custom event in my polymer component by calling

this.dispatchEvent(new CustomEvent('session-disconnected', {}));

and I try to catch it on the serverside with

@EventHandler
public void onSessionDisconnected() {

}

Unfortunately the method on the serverside is not invoked. What am I doing wrong here?

Hi.

The @EventHandler only works with polymer events like on-click also the name should be the same.
This would mean that in the template you would have <div on-click="sessionDisconnected">on-Event</div> and on the server

@EventHandler
private void sessionDisconnected() {
  System.out.println("Session info");
}

To use the dispatchEvent with a CustomEvent you should register an EventListener for instance getElement().addEventListener("sessionDisconnected", disconnect -> System.out.println("Session info"));
This should then fire when running this.dispatchEvent(new CustomEvent('sessionDisconnected', {}));

Hope this helps.

  • Mikael

Mikael Grankvist:
Hi.

The @EventHandler only works with polymer events like on-click also the name should be the same.
This would mean that in the template you would have <div on-click="sessionDisconnected">on-Event</div> and on the server

@EventHandler
private void sessionDisconnected() {
  System.out.println("Session info");
}

To use the dispatchEvent with a CustomEvent you should register an EventListener for instance getElement().addEventListener("sessionDisconnected", disconnect -> System.out.println("Session info"));
This should then fire when running this.dispatchEvent(new CustomEvent('sessionDisconnected', {}));

Hope this helps.

  • Mikael

Hi Mikael,
I’m trying to reproduce your approach.

My bulk-view.html component rise a CustomEvent like this:

`this.dispatchEvent(new CustomEvent('serverEvent', {}));`

and this is the Java server-side implementation:

```
...
@HtmlImport("src/views/setting/bulk/bulk-view.html")
public class BulkView extends PolymerTemplate<TemplateModel> {

@Override
	protected void onAttach(AttachEvent attachEvent) {
		getElement().addEventListener("serverEvent", e -> System.out.println(e));
		super.onAttach(attachEvent);
	}
...
```

Unfortunalety the java code is not triggered.