From b7cb02ed42cd4ce0601789c10f2b4cfeca5f0fad Mon Sep 17 00:00:00 2001 From: crisbeto Date: Mon, 8 Jan 2018 21:10:50 +0100 Subject: [PATCH] refactor(selection-model): expose source model in change event Exposes the selection model that dispatched an event inside the event itself. This is mostly for convenience, because it allows the consumer to access the selected value and other properties without having to reach outside the callback. Relates to the discussion in #8599. --- src/cdk/collections/selection.spec.ts | 13 +++++++++++++ src/cdk/collections/selection.ts | 12 +++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/cdk/collections/selection.spec.ts b/src/cdk/collections/selection.spec.ts index ac89da41ea6e..881088fbcad4 100644 --- a/src/cdk/collections/selection.spec.ts +++ b/src/cdk/collections/selection.spec.ts @@ -85,6 +85,19 @@ describe('SelectionModel', () => { }); describe('onChange event', () => { + it('should return the model that dispatched the event', () => { + let model = new SelectionModel(); + let spy = jasmine.createSpy('SelectionModel change event'); + + model.onChange!.subscribe(spy); + model.select(1); + + let event = spy.calls.mostRecent().args[0]; + + expect(spy).toHaveBeenCalled(); + expect(event.source).toBe(model); + }); + it('should return both the added and removed values', () => { let model = new SelectionModel(); let spy = jasmine.createSpy('SelectionModel change event'); diff --git a/src/cdk/collections/selection.ts b/src/cdk/collections/selection.ts index 4f33ef51986f..aafc6169f7ed 100644 --- a/src/cdk/collections/selection.ts +++ b/src/cdk/collections/selection.ts @@ -122,7 +122,7 @@ export class SelectionModel { this._selected = null; if (this._selectedToEmit.length || this._deselectedToEmit.length) { - const eventData = new SelectionChange(this._selectedToEmit, this._deselectedToEmit); + const eventData = new SelectionChange(this, this._selectedToEmit, this._deselectedToEmit); if (this.onChange) { this.onChange.next(eventData); @@ -178,11 +178,17 @@ export class SelectionModel { } /** - * Describes an event emitted when the value of a MatSelectionModel has changed. + * Event emitted when the value of a MatSelectionModel has changed. * @docs-private */ export class SelectionChange { - constructor(public added?: T[], public removed?: T[]) { } + constructor( + /** Model that dispatched the event. */ + public source: SelectionModel, + /** Options that were added to the model. */ + public added?: T[], + /** Options that were removed from the model. */ + public removed?: T[]) {} } /**