2017-05-24 43 views

回答

1

感谢您的询问。

有几种方法可以做到这一点。

(1)创建在B事件处理程序转发从C

@Component(
    selector: 'b', 
    directives: const [C], 
    template: '<c (event)="cDidEvent()"></c>', 
) 
class B { 
    final _onEvent = new StreamController(); 
    Stream get onEvent => _onEvent.stream; 

    void cDidEvent() { 
    _onEvent.add(null); 
    } 
} 

(2)使用依赖注入。

这需要在组件之间进行更深的耦合,所以它不适用于所有设计,但在某些情况下它可能有意义。

abstract class OnEvent { 
    /// Called when an event happens. 
    void onEvent(); 
} 

@Component(
    selector: 'a', 
    directives: const [B], 
    template: '<b></b>', 
    providers: const [ 
    const Provider(OnEvent, useExisting: A), 
    ], 
) 
class A implements OnEvent { 
    @override 
    void onEvent() { 
    print('>>> An event was triggered!'); 
    } 
} 

class C { 
    final OnEvent _eventHandler; 

    C(this._eventHandler); 

    void onSomeAction() { 
    _eventHandler.onEvent(); 
    } 
} 
0

我认为这是更容易只是创建在成分A和成分C.

这里注入了“事件总线”单服务是代码:

class Event { 
    // your data 
} 

@Injectable() 
class EventBus { 

    final StreamController<Event> _onEventStream = new StreamController<Event>(); 
    Stream<Selection> 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 */) 
    } 
} 
相关问题