AngularJS 中 $broadcast()、$emit() 和 $on() 的使用 [英] Usage of $broadcast(), $emit() And $on() in AngularJS

查看:24
本文介绍了AngularJS 中 $broadcast()、$emit() 和 $on() 的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 $Broadcast()$Emit()$On() 用于在一个控制器中引发事件并在另一个控制器中处理.如果可能的话,由于我是 angular JS 的新手,所以有人能给我一些关于上述三个用法的实时示例吗?

I understand that $Broadcast(), $Emit() And $On() are used to raise an event in one controller and handling in another controller. If possible, can someone just give me some real time example on the usage of above three as I am new to angular JS?

我已经浏览了以下链接并了解基本用法.

I have gone through the following links and understand the basic usage.

http://www.binaryintellect.net/articles/5d8be0b6-e294-457e-82b0-ba7cc10cae0e.aspx

推荐答案

$emit

它通过作用域层次向上调度事件名称,并通知注册的 $rootScope.Scope 侦听器.事件生命周期从调用 $emit 的范围开始.事件向上遍历根作用域,并沿途调用所有已注册的侦听器.如果其中一个侦听器取消该事件,该事件将停止传播.

It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $emit was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

$broadcast

它将事件名称向下调度到所有子作用域(及其子作用域)并通知注册的 $rootScope.Scope 侦听器.事件生命周期从调用 $broadcast 的范围开始.此范围内事件的所有侦听器都会收到通知.之后,事件向下遍历子作用域,并沿途调用所有已注册的侦听器.活动不可取消.

It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.

$on

它监听给定类型的事件.它可以捕获$broadcast$emit 调度的事件.

It listen on events of a given type. It can catch the event dispatched by $broadcast and $emit.

视觉演示:

Demo 工作代码,直观展示作用域树(父/子关系):
http://plnkr.co/edit/am6IDw?p=preview

Demo working code, visually showing scope tree (parent/child relationship):
http://plnkr.co/edit/am6IDw?p=preview

演示方法调用:

  $scope.$on('eventEmitedName', function(event, data) ...
  $scope.broadcastEvent
  $scope.emitEvent

这篇关于AngularJS 中 $broadcast()、$emit() 和 $on() 的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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