angularJS $on event handler trigger order

前端 未结 6 987
我在风中等你
我在风中等你 2021-02-01 17:42

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

  1. How is defined the order in which handlers listening to the same event are triggered?
6条回答
  •  攒了一身酷
    2021-02-01 18:21

    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.

提交回复
热议问题