angularJS $on event handler trigger order

前端 未结 6 980
我在风中等你
我在风中等你 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:12

    It is a bit hacky and absolutely not recommended to use in your design, but sometimes you don't have a choice (been there so many times).

    $rootScope.$on('someEvent', () => {
        setTimeout(eventHandler1, 1);
    });
    
    $rootScope.$on('someEvent', eventHandler2);
    
    const eventHandler1 = () => {
        console.log('This one runs last');
    };
    
    const eventHandler2 = () => {
        console.log('This one runs first');
    };
    

    As you can see from the example, I have used setTimeout to trick the order of running the actual handler and make the eventHandler1 handler to run last, although it has been called first.

    To set the execution priority, just change the setTimeout delay as necessary.

    This is not ideal and is only suited for specific cases.

提交回复
热议问题