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

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

问题描述

试图找到AngularJS $ rootScope。$广播的一些基本信息,但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?

此外,内约翰爸爸的热毛巾模板有共同的模块中的自定义函数名为 $广播

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。$广播吗?

2)之间有什么 $ rootScope。$广播的区别 $ rootScope。$ broadcast.apply

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

推荐答案

$ rootScope 基本功能是作为一个事件监听器和调度。

$rootScope basically functions as an event listener and dispatcher.

要回答它是如何使用的问题,它配合使用 rootScope $在;

To answer the question of how it is used, it used in conjunction with rootScope.$on;

$rootScope.$broadcast("hi");

$rootScope.$on("hi", function(){
    //do something
});

然而,这是一个不好的做法,使用 $ rootScope 作为自己的应用程序的通用事件服务,因为你很快就会在每一个应用程序依赖于$的情况下结束了rootScope,你不知道组件在听什么事件是什么。

However, it is a bad practice to use $rootScope as your own app's general event service, since you will quickly end up in a situation where every app depends on $rootScope, and you do not know what components are listening to what events.

最好的做法是为您要听或广播的每个自定义事件创建服务。

The best practice is to create a service for each custom event you want to listen to or broadcast.

.service("hiEventService",function($rootScope) {
    this.broadcast = function() {$rootScope.$broadcast("hi")}
    this.listen = function(callback) {$rootScope.$on("hi",callback)}
})

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

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