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

前端 未结 1 768
不知归路
不知归路 2021-02-02 18:05

I have class like this :

class BaseModel {
  Map objects;

  // define constructor here

  fetch() {
    // fetch json from server and then load it to objects
          


        
1条回答
  •  星月不相逢
    2021-02-02 18:50

    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

    0 讨论(0)
提交回复
热议问题