$rootScope.$broadcast 与 $scope.$emit [英] $rootScope.$broadcast vs. $scope.$emit

查看:34
本文介绍了$rootScope.$broadcast 与 $scope.$emit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

既然 $broadcast$emit 之间的性能差异已经消除,还有什么理由更喜欢 $scope.$emit$rootScope.$broadcast?

Now that the performance difference between $broadcast and $emit has been eliminated, is there any reason to prefer $scope.$emit to $rootScope.$broadcast?

他们是不同的,是的.

$emit 仅限于作用域层次结构(向上) - 如果它适合您的设计,这可能很好,但在我看来这是一个相当随意的限制.

$emit is restricted to the scope hierarchy (upwards) - this may be good, if it fits your design, but it seems to me a rather arbitrary restriction.

$rootScope.$broadcast 适用于所有选择侦听事件,在我看来这是一个更明智的限制.

$rootScope.$broadcast works across all that choose to listen to the event, which is a more sensible restriction in my mind.

我错过了什么吗?

为了回应答案澄清一下,派遣的方向不是我所追求的问题.$scope.$emit 向上调度事件,$scope.$broadcast - 向下调度.但是为什么不总是使用 $rootScope.$broadcast 来覆盖所有预期的听众?

To clarify in response to an answer, the direction of the dispatch is not the issue I'm after. $scope.$emit dispatches the event upwards, and $scope.$broadcast - downwards. But why not always use $rootScope.$broadcast to reach all the intended listeners?

推荐答案

tl;dr (这个 tl;dr 来自 @sp00m 的回答如下)

tl;dr (this tl;dr is from @sp00m's answer below)

$emit 向上调度事件 ... $broadcast 向下调度事件

$emit dispatches an event upwards ... $broadcast dispatches an event downwards

详细说明

$rootScope.$emit 只允许其他 $rootScope 侦听器捕获它.当您不希望每个 $scope 都得到它时,这很好.主要是高层沟通.可以把它想象成成年人在一个房间里互相交谈,这样孩子们就听不到他们的声音了.

$rootScope.$emit only lets other $rootScope listeners catch it. This is good when you don't want every $scope to get it. Mostly a high level communication. Think of it as adults talking to each other in a room so the kids can't hear them.

$rootScope.$broadcast 是一种让几乎所有东西都能听到的方法.这相当于父母大喊晚饭准备好让家里的每个人都听到.

$rootScope.$broadcast is a method that lets pretty much everything hear it. This would be the equivalent of parents yelling that dinner is ready so everyone in the house hears it.

$scope.$emit 是当您希望 $scope 及其所有父项和 $rootScope 听到事件时.这是一个孩子在家里向父母抱怨(但不是在其他孩子可以听到的杂货店).

$scope.$emit is when you want that $scope and all its parents and $rootScope to hear the event. This is a child whining to their parents at home (but not at a grocery store where other kids can hear).

$scope.$broadcast 用于 $scope 本身及其子项.这是一个孩子对它的毛绒动物耳语,这样他们的父母就听不见了.

$scope.$broadcast is for the $scope itself and its children. This is a child whispering to its stuffed animals so their parents can't hear.

这篇关于$rootScope.$broadcast 与 $scope.$emit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆