结合使用$emit和$broadcast是一个好的实践吗?

3
我知道$emit和$broadcast之间的区别,但是我想知道在层次结构变得更加复杂的情况下,将两者结合起来是否是一个好的实践方法呢?
考虑以下情况:
- 我有两个相邻的视图(称为Child1、Child2),它们位于一个主视图(Parent1)中,我希望在这两个相邻的视图之间传递一个事件。 - 在未来,Child1、Child2视图可能会有父级。
在我的以下示例中,我将“wake up”字符串从Child1传递到Child2(而Parent1是传递此数据的人)。
技术上发生了什么:
1. Child1 发送 'wake up' ($emit) 2. Parent1 捕捉此事件 ($on),并发送给 Child2 ($broadcast) 3. Child2 被告知($on)
代码:
function ControllerParent1($scope) {
    $scope.$on('myEmit', function(event, args) {
        $scope.$broadcast('myBroadcast', args.message); //Step2
    };
}

function ControllerChild1($scope) {
    $scope.$on('myEmit', function(event, args) {
        $scope.$emit('send', {message: 'wake up'}); //Step1
    });        
}

function ControllerChild2($scope) {
    $scope.$on('myBroadcast', function(event, args) {
        $scope.message = args.message; //Step3
    });
}

对我来说,这听起来非常技术化,我对这种做法感到疑惑,它是在Angular中正确的工作方式吗?它可能在未来处理起来更加复杂。


我认为你应该考虑使用$rootScope.$emit$rootScope.$on,这将仅将事件传播到$rootScope。关于性能优化的更多细节,我强烈建议你阅读这篇文章 - Pankaj Parkar
1个回答

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接