Skip to content
Browse files

fix(ivy): maintain coalesced listeners order (#32484)

Prior to this commit, listeners order was not preserved in case we coalesce them to avoid triggering unnecessary change detection cycles. For performance reasons we were attaching listeners to existing events at head (always using first listener as an anchor), to avoid going through the list, thus breaking the order in which listeners are registered. In some scenarios this order might be important (for example with `ngModelChange` and `input` listeners), so this commit updates the logic to put new listeners at the end of the list. In order to avoid performance implications, we keep a pointer to the last listener in the list, so adding a new listener takes constant amount of time.

PR Close #32484
  • Loading branch information...
AndrewKushnir authored and matsko committed Sep 4, 2019
1 parent a9ff48e commit 098feec4a03b95d808ba01db183a76d0da289ff2
@@ -149,9 +149,13 @@ function listenerInternal(
existingListener = findExistingListener(lView, eventName, tNode.index);
if (existingListener !== null) {
// Attach a new listener at the head of the coalesced listeners list.
(<any>listenerFn).__ngNextListenerFn__ = (<any>existingListener).__ngNextListenerFn__;
(<any>existingListener).__ngNextListenerFn__ = listenerFn;
// Attach a new listener to coalesced listeners list, maintaining the order in which
// listeners are registered. For performance reasons, we keep a reference to the last
// listener in that list (in `__ngLastListenerFn__` field), so we can avoid going through
// the entire set each time we need to add a new listener.
const lastListenerFn = (<any>existingListener).__ngLastListenerFn__ || existingListener;
lastListenerFn.__ngNextListenerFn__ = listenerFn;
(<any>existingListener).__ngLastListenerFn__ = listenerFn;
processOutputs = false;
} else {
// The first argument of `listen` function in Procedural Renderer is:
@@ -238,5 +238,38 @@ describe('event listeners', () => {

it('should maintain the order in which listeners are registered', () => {
const log: string[] = [];
selector: 'my-comp',
template: '<button dirA dirB (click)="count()">Click me!</button>',
class MyComp {
counter = 0;
count() { log.push(''); }

@Directive({selector: '[dirA]'})
class DirA {
count() { log.push(''); }

@Directive({selector: '[dirB]'})
class DirB {
count() { log.push(''); }

TestBed.configureTestingModule({declarations: [MyComp, DirA, DirB]});
const fixture = TestBed.createComponent(MyComp);

const button = fixture.nativeElement.firstChild;;

expect(log).toEqual(['', '', '']);

0 comments on commit 098feec

Please sign in to comment.
You can’t perform that action at this time.