$ rootScope。$广播与$范围。$放出 [英] $rootScope.$broadcast vs. $scope.$emit
问题描述
现在 $广播之间的性能差异
和 $发出
已经被淘汰了,没有任何理由为preFER $范围。$发出
到 $ rootScope。$广播
?
Now that the performance difference between $broadcast
and $emit
has been eliminated, is there any reason to prefer $scope.$emit
to $rootScope.$broadcast
?
他们是不同的,是的。
They are different, yes.
$发出
被限制的范围层次结构(向上) - 这可能是好的,如果它符合你的设计,但在我看来,一个相当任意的限制
$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。$广播
可以跨所有的选择的听的事件,这是在我的脑海一个更明智的限制。
$rootScope.$broadcast
works across all that choose to listen to the event, which is a more sensible restriction in my mind.
我缺少的东西吗?
编辑:
要响应于一个答案澄清,调度的方向不我后的问题。 $ $范围发出
向上调度该事件,而 $ $范围广播
- 向下。但是,为什么不总是使用 $ rootScope。$广播
来达到所有预期的听众?
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?
推荐答案
$ rootScope。$发出
只能让其他 $ rootScope
听众抓住它。这是一件好事,当你不希望每个 $范围
来得到它。大多是高层次的沟通。可以把它当作成年人在一个房间里互相交谈,让孩子们可以不听。
$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。$广播
是让pretty所有事情听到它的方法。这将是父母相当于大呼小叫,晚餐准备好所以大家在家里听到它。
$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.
$范围。$发出
是当你想要的 $范围
及其所有的父母和 $ 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
is for the $scope
itself and its children. This is a child whispering to its stuffed animals so their parents can't hear.
TL;博士(这TL;博士是 @ sp00m下面接听)
tl;dr (this tl;dr is from @sp00m answer below)
$ EMIT调度一个事件向上... $广播向下调度一个事件
$emit dispatches an event upwards ... $broadcast dispatches an event downwards
这篇关于$ rootScope。$广播与$范围。$放出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!