为什么我们在 AngularJS 中使用 $rootScope.$broadcast? [英] Why do we use $rootScope.$broadcast in AngularJS?

查看:55
本文介绍了为什么我们在 AngularJS 中使用 $rootScope.$broadcast?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找到 AngularJS $rootScope.$broadcast 的一些基本信息,但是 AngularJS 文档并没有多大帮助.简单地说,我们为什么要使用它?

Tried to find some basic information for AngularJS $rootScope.$broadcast, But the AngularJS documentation doesn't help much. In easy words why do we use this?

此外,在 John Papa 的 Hot Towel 模板中,有一个自定义函数名为 $broadcast 的公共模块:

Also, inside John Papa's Hot Towel template there is a custom function in the common module named $broadcast:

function $broadcast() {
    return $rootScope.$broadcast.apply($rootScope, arguments);
}

我不明白这是在做什么.所以这里有几个基本问​​题:

I did not understand what this is doing. So here are couple of basic questions:

1) $rootScope.$broadcast 有什么作用?

2) $rootScope.$broadcast$rootScope.$broadcast.apply 有什么区别?

2) What is the difference between $rootScope.$broadcast and $rootScope.$broadcast.apply?

推荐答案

  1. $rootScope.$broadcast 有什么作用?

$rootScope.$broadcast 正在通过应用程序范围发送事件.该应用程序的任何子范围都可以使用简单的方法捕获它:$scope.$on().

$rootScope.$broadcast is sending an event through the application scope. Any children scope of that app can catch it using a simple: $scope.$on().

当您想要访问不是直接父级的范围(例如父级的分支)时,发送事件特别有用

It is especially useful to send events when you want to reach a scope that is not a direct parent (A branch of a parent for example)

!!!然而,不要做 的一件事是使用控制器中的 $rootScope.$on.$rootScope 是应用程序,当你的控制器被销毁时,事件监听器仍然存在,当你的控制器再次创建时,它只会堆积更多的事件监听器.(所以一个广播会被多次捕获).使用 $scope.$on() 代替,监听器也会被销毁.

!!! One thing to not do however is to use $rootScope.$on from a controller. $rootScope is the application, when your controller is destroyed that event listener will still exist, and when your controller will be created again, it will just pile up more event listeners. (So one broadcast will be caught multiple times). Use $scope.$on() instead, and the listeners will also get destroyed.

$rootScope.$broadcast 和有什么区别?$rootScope.$broadcast.apply?

有时您必须使用 apply(),尤其是在使用指令和其他 JS 库时.但是,由于我不知道该代码库,因此我无法判断此处是否是这种情况.

Sometimes you have to use apply(), especially when working with directives and other JS libraries. However since I don't know that code base, I wouldn't be able to tell if that's the case here.

这篇关于为什么我们在 AngularJS 中使用 $rootScope.$broadcast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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