2014-10-03 81 views
3

我想从一个组件通过自定义事件其父组件/控制器角镖组件事件

confirm.html

<div class="comfirm-component"> 
    <content></content> 
    <a href="#" ng-click="ctrl.yes()">Yes</a> 
    <a href="#" ng-click="ctrl.no()">No</a> 
</div> 

confirm.dart

@Component(
    selector: "confirm-component", 
    templateUrl: 'confirm.html', 
    useShadowDom: false, 
    publishAs: "ctrl" 
) 
class ConfirmComponent { 
    void yes(){ 
     print('yes'); 
     // Fire confirm-yes event 
    } 

    void no(){ 
     print('no'); 
     // Fire confirm-no event 
    } 
} 

是有这样的事情吗?:

<confirm-component on-confirm-yes="doSomething()" on-confirm-no="doSomethingElse()"> 
    Do you want to delete 
</confirm-component> 

我可以使用一个普通的StreamController,但然后我不得不将我的组件与代码连接。

confirmComponent.onConfirmYes.listen() 
confirmComponent.onConfirmNo.listen() 

我也发现了这一点: How to communicate between Angular DART controllers

这: angulardart components - dispatch custom event

在两个踏板scope.emit被提及。但我没有找到一种方法来使用它与组件而不是控制器。有没有一个完整的例子vor angular.dart v0.14.0?

是scope.emit我正在寻找的东西?

回答

4

这应该是一样的,只需将一个作用域参数添加到构造函数中,以便组件获取注入的作用域。

有在角0.14.0 https://github.com/angular/angular.dart/commit/181f01448555c475869505491159045904e5dc89

相关的变化我还没有尝试过这一点。 从说明你需要根据从君特的回答我建立了这个工作示例实现ScopeAware

@Component(...) 
class MyComponent implements ScopeAware { 
    Watch watch; 
    MyComponent(Dependency myDep) { 
    // It is an error to add a Scope/RootScope argument to the ctor and will result in a DI 
    // circular dependency error - the scope is never accessible in the class constructor 
    } 

    void set scope(Scope scope) { 
    // with this scope you should be able to use emit 
    // This setter gets called to initialize the scope 
    watch = scope.rootScope.watch("expression", (v, p) => ...); 
    } 
} 
2

@Component(
    selector: "confirm-component", 
    templateUrl: 'component/confirm.html', 
    useShadowDom: false, 
    publishAs: "ctrl" 
) 

class ConfirmComponent implements ScopeAware { 
    Scope scope; 

    void yes(){ 
     scope.emit('confirm', 'yes'); 
    } 

    void no(){ 
     scope.emit('confirm', 'no'); 
    } 
} 

@Component(
    selector: "my-component", 
    templateUrl: 'component/my.html', 
    useShadowDom: false, 
    publishAs: "ctrl" 
) 
class MyComponent implements ScopeAware{ 

    void set scope(Scope scope) { 
     Stream mystream = scope.on('confirm'); 
     mystream.listen((event){ 
      print('confirmed: ' + event.data); 
     }); 
    } 
} 
+0

你可以简单地写'scope.on(“确认” )。听(...)'。如果你想取消订阅,你应该存储从'listen'返回的'StreamSubscription',你可以调用'cancel()'来取消订阅事件。 – 2014-10-03 09:04:52