Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dart how to create, listen, and emits custom event?

Tags:

dart

I have class like this :

class BaseModel {
  Map objects;

  // define constructor here

  fetch() {
    // fetch json from server and then load it to objects
    // emits an event here
  }

}

Like backbonejs i want to emits a change event when i call fetch and create a listener for change event on my view.

But from reading the documentation, i don't know where to start since there are so many that points to event, like Event Events EventSource and so on.

Can you guys give me a hint?

like image 625
Otskimanot Sqilal Avatar asked Mar 30 '13 10:03

Otskimanot Sqilal


1 Answers

I am assuming you want to emit events that do not require the presence of dart:html library.

You can use the Streams API to expose a stream of events for others to listen for and handle. Here is an example:

import 'dart:async';

class BaseModel {
  Map objects;
  StreamController fetchDoneController = new StreamController.broadcast();

  // define constructor here

  fetch() {
    // fetch json from server and then load it to objects
    // emits an event here
    fetchDoneController.add("all done"); // send an arbitrary event
  }

  Stream get fetchDone => fetchDoneController.stream;

}

Then, over in your app:

main() {
  var model = new BaseModel();
  model.fetchDone.listen((_) => doCoolStuff(model));
}

Using the native Streams API is nice because it means you don't need the browser in order to test your application.

If you are required to emit a custom HTML event, you can see this answer: https://stackoverflow.com/a/13902121/123471

like image 134
Seth Ladd Avatar answered Sep 28 '22 10:09

Seth Ladd