Skip to content

Commit

Permalink
fix(dropdown): don't emit duplicate change events
Browse files Browse the repository at this point in the history
Fixes #694

Closes #695
  • Loading branch information
pkozlowski-opensource committed Sep 7, 2016
1 parent e032669 commit 2e529e3
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 4 deletions.
40 changes: 40 additions & 0 deletions src/dropdown/dropdown.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,40 @@ describe('ngb-dropdown', () => {

expect(fixture.componentInstance.isOpen).toBe(false);
});

it('should not raise open events if open state does not change', () => {
const html = `
<button (click)="drop.open(); $event.stopPropagation()">Open</button>
<button (click)="drop.close(); $event.stopPropagation()">Close</button>
<div ngbDropdown (openChange)="recordStateChange($event)" #drop="ngbDropdown"></div>`;

const fixture = createTestComponent(html);
const compiled = fixture.nativeElement;
let buttonEls = compiled.querySelectorAll('button');

expect(fixture.componentInstance.isOpen).toBe(false);
expect(fixture.componentInstance.stateChanges).toEqual([]);

buttonEls[1].click(); // close a closed one
fixture.detectChanges();
expect(fixture.componentInstance.isOpen).toBe(false);
expect(fixture.componentInstance.stateChanges).toEqual([]);

buttonEls[0].click(); // open a closed one
fixture.detectChanges();
expect(fixture.componentInstance.isOpen).toBe(true);
expect(fixture.componentInstance.stateChanges).toEqual([true]);

buttonEls[0].click(); // open an opened one
fixture.detectChanges();
expect(fixture.componentInstance.isOpen).toBe(true);
expect(fixture.componentInstance.stateChanges).toEqual([true]);

buttonEls[1].click(); // close an opened one
fixture.detectChanges();
expect(fixture.componentInstance.isOpen).toBe(false);
expect(fixture.componentInstance.stateChanges).toEqual([true, false]);
});
});

describe('ngb-dropdown-toggle', () => {
Expand Down Expand Up @@ -324,4 +358,10 @@ describe('ngb-dropdown-toggle', () => {
@Component({selector: 'test-cmp', template: ''})
class TestComponent {
isOpen = false;
stateChanges = [];

recordStateChange($event) {
this.stateChanges.push($event);
this.isOpen = $event;
}
}
12 changes: 8 additions & 4 deletions src/dropdown/dropdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,20 @@ export class NgbDropdown {
* Opens the dropdown menu of a given navbar or tabbed navigation.
*/
open(): void {
this._open = true;
this.openChange.emit(true);
if (!this._open) {
this._open = true;
this.openChange.emit(true);
}
}

/**
* Closes the dropdown menu of a given navbar or tabbed navigation.
*/
close(): void {
this._open = false;
this.openChange.emit(false);
if (this._open) {
this._open = false;
this.openChange.emit(false);
}
}

/**
Expand Down

0 comments on commit 2e529e3

Please sign in to comment.