angular五大服务顺序_angularJS $事件处理程序的触发顺序

I was wondering two things, in the context of angularJS event handling.

How is defined the order in which handlers listening to the same event are triggered?

Is it a sign of a bad design if you start wondering about this?

After reading documentation on angular $on, $broadcast and $emit as well as native DOM event flow I think I understand in which order event handlers will be trigger in different scopes. The problem is when several handlers listen in the same scope ($rootScope for example) from various places (Controllers vs Services for example).

To illustrate the problem I have put together a jsfiddle with one controller and two services, all communicating through $rootScope http://jsfiddle.net/Z84tX/

Thanks

解决方案

Very good question.

Event handlers are executed in order of initialization.

I haven't really thought about this before, because my handlers never needed to know which one run first, but by the look of you fiddle I can see that the handlers are called in the same order in which they are initialized.

In you fiddle you have a controller controllerA which depends on two services, ServiceA and ServiceB:

myModule

.controller('ControllerA',

[

'$scope',

'$rootScope',

'ServiceA',

'ServiceB',

function($scope, $rootScope, ServiceA, ServiceB) {...}

]

);

Both services and the controller define an event listener.

Now, all dependencies need to be resolved before being injected, which means that both services will be initialized before being injected into the controller. Thus, handlers defined in the services will be called first, because service factories are initialized before controller.

Then, you may also observe that the services are initialized in order they are injected. So ServiceA is initialized before ServiceB because they are injected in that order into the controller. If you changed their order inside the controller signature you'll see that their initilization order is also changed (ServiceB comes before ServiceA).

So, after the services are initialized, the controller gets initialized as well, and with it, the event handler defined within.

So, the end result is, on $broadcast, the handlers will be executed in this order: ServiceA handler, ServiceB handler, ControllerA handler.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值