refactor(selection-model): expose source model in change event (#9288)

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.
This commit is contained in:
Kristiyan Kostadinov
2018-01-23 16:58:15 +01:00
committed by Jeremy Elbourn
parent 278e25ac04
commit bb9da60282
2 changed files with 22 additions and 3 deletions
+13
View File
@@ -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');
+9 -3
View File
@@ -122,7 +122,7 @@ export class SelectionModel<T> {
this._selected = null;
if (this._selectedToEmit.length || this._deselectedToEmit.length) {
const eventData = new SelectionChange(this._selectedToEmit, this._deselectedToEmit);
const eventData = new SelectionChange<T>(this, this._selectedToEmit, this._deselectedToEmit);
if (this.onChange) {
this.onChange.next(eventData);
@@ -178,11 +178,17 @@ export class SelectionModel<T> {
}
/**
* 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<T> {
constructor(public added?: T[], public removed?: T[]) { }
constructor(
/** Model that dispatched the event. */
public source: SelectionModel<T>,
/** Options that were added to the model. */
public added?: T[],
/** Options that were removed from the model. */
public removed?: T[]) {}
}
/**