Question

In this useful post we can learn how to listen to dispatched custom events by way of inline markup in the template: How do I fire a custom event from Polymer Dart? I wonder if it's possible to do the same in the dart-script when custom elements are dynamically created, like this:

var myElement = new Element.tag('my-element');
Was it helpful?

Solution

You need for each event handler in your component an EventStreamProvider (static)
and a getter for easy access.

static const EventStreamProvider<CustomEvent> logoutEvent = 
    const EventStreamProvider<CustomEvent>("my-logout");
Stream<CustomEvent> get onLogout =>  MyElement.logoutEvent.forTarget(this);

You fire an event like

this.dispatchEvent(new CustomEvent("my-logout", detail: {'someData': 'bla'}));

// Polymer provides a shortcut for this
fire('my-logout', detail: {'someData': 'bla'});

You subscribe to this event like

mySesson.onLogout.listen((e) => doSomething());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top