gpt4 book ai didi

angularjs - 结合 $emit 和 $broadcast 是一个好的做法吗?

转载 作者:行者123 更新时间:2023-12-02 12:25:51 24 4
gpt4 key购买 nike

我知道 $emit 和 $broadcast 之间的区别,但我想知道将两者结合起来是否是一个好的做法,而将来的层次结构可能会更加复杂?

考虑以下情况:

  • 我在主视图 (Parent1) 内有两个邻居 View (我们称它们为 Child1、Child2),我想在两个邻居之间传递一个事件。
  • 将来,Child1、Child2 View 可能有 future 的父级。

在下面的示例中,我将“唤醒”字符串从 Child1 传递到 Child2(而 Parent1 是传递此数据的人)。技术上一步步发生的事情:

  1. Child1 发送“唤醒”($emit)
  2. 父级 1 捕获 ($on) 此事件,并将其发送给子级 2 ($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 工作的正确方法吗?以后处理起来可能会更复杂。

最佳答案

如果您愿意为您的应用程序提供 future 证明,您可以使用发布/订阅模式。这样,您的 Controller 就可以发布他们想要的事件并订阅他们感兴趣的任何事件,而无需在 ($scope/$rootScope).($emit/$broadcast) 上强耦合。

有关本文的更多信息:http://eburley.github.io/2013/01/31/angularjs-watch-pub-sub-best-practices.html

这里有一个示例实现:https://github.com/georapbox/angular-PubSub

关于angularjs - 结合 $emit 和 $broadcast 是一个好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35196452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com