AngularDart: How do you pass an event from a Child component to a second level parent

前端 未结 2 1351
春和景丽
春和景丽 2021-01-24 01:50

I am using StreamControllers with Events, and essentially I have a 3 level component heirarchy lets call them, A,B,C. The heirarchy is A -> B -> C.

The origin of the eve

2条回答
  •  离开以前
    2021-01-24 02:19

    I think it is easier just to create an "event bus" singleton service that is injected in Component A and Component C.

    Here is the code:

    class Event {
         // your data
    }
    
    @Injectable()
    class EventBus {
    
        final StreamController _onEventStream = new StreamController();
        Stream onEventStream = null;
    
        static final EventBus _singleton = new EventBus._internal(); 
    
        factory EventBus() {
             return _singleton;
        }
    
        EventBus._internal() {
             onEventStream = _onEventStream.stream;
        }
    
        onEvent(Event event) {
             _onEventStream.add(selection);
        }
    }
    
    
    @Component(
       selector: 'C',
       templateUrl: 'C.html',
       providers: const [
           EventBus
       ]
     )
     class C {
    
         final EventBus _eventBus;
    
         C(this._eventBus);
    
         onAction() {
             _eventBus.onEvent(new Event());
        }
     }
    
    
    @Component(
        selector: 'A',
        templateUrl: 'A.html',
        providers: const [
            EventBus
        ]
    )
    class A {
    
        final EventBus _eventBus;
    
        A(this._eventBus) {
            _eventBus.onEventStream.listen((Event e) => /* do something with the event */)
        }
    }
    

提交回复
热议问题