失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > angular五大服务顺序 angularJS $事件处理程序的触发顺序

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

时间:2019-11-10 08:53:52

相关推荐

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 /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.

如果觉得《angular五大服务顺序 angularJS $事件处理程序的触发顺序》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。