Skip to content

Commit 710c7f7

Browse files
author
Matt Lewis
committed
fix(draggable): dispose of observables when the component is destroyed
1 parent 6016f12 commit 710c7f7

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

src/draggable.directive.ts

+8-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {Directive, HostListener, OnInit, ElementRef, Renderer, Output, EventEmitter, Input} from '@angular/core';
1+
import {Directive, HostListener, OnInit, ElementRef, Renderer, Output, EventEmitter, Input, OnDestroy} from '@angular/core';
22
import {Subject} from 'rxjs/Subject';
33
import {Observable} from 'rxjs/Observable';
44
import 'rxjs/add/observable/merge';
@@ -13,7 +13,7 @@ type Coordinates = {x: number, y: number};
1313
@Directive({
1414
selector: '[mwlDraggable]'
1515
})
16-
export class Draggable implements OnInit {
16+
export class Draggable implements OnInit, OnDestroy {
1717

1818
@Input() dropData: any;
1919

@@ -61,7 +61,6 @@ export class Draggable implements OnInit {
6161

6262
});
6363

64-
// TODO - unsubscribe from this on destroy
6564
mouseDrag.subscribe(({x, y, currentDrag}) => {
6665
this.dragging.next({x, y});
6766
this.setCssTransform(`translate(${x}px, ${y}px)`);
@@ -70,6 +69,12 @@ export class Draggable implements OnInit {
7069

7170
}
7271

72+
ngOnDestroy(): void {
73+
this.mouseDown.complete();
74+
this.mouseMove.complete();
75+
this.mouseUp.complete();
76+
}
77+
7378
/**
7479
* @private
7580
*/

test/draggable.directive.spec.ts

+21
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,25 @@ describe('draggable directive', () => {
5959
expect(draggableElement.style.transform).to.equal('');
6060
});
6161

62+
it('should end the mouseUp observable when the component is destroyed', () => {
63+
const complete: sinon.SinonSpy = sinon.spy();
64+
fixture.componentInstance.draggable.mouseUp.subscribe({complete});
65+
fixture.destroy();
66+
expect(complete).to.have.been.calledOnce;
67+
});
68+
69+
it('should end the mouseDown observable when the component is destroyed', () => {
70+
const complete: sinon.SinonSpy = sinon.spy();
71+
fixture.componentInstance.draggable.mouseDown.subscribe({complete});
72+
fixture.destroy();
73+
expect(complete).to.have.been.calledOnce;
74+
});
75+
76+
it('should end the mouseMove observable when the component is destroyed', () => {
77+
const complete: sinon.SinonSpy = sinon.spy();
78+
fixture.componentInstance.draggable.mouseMove.subscribe({complete});
79+
fixture.destroy();
80+
expect(complete).to.have.been.calledOnce;
81+
});
82+
6283
});

0 commit comments

Comments
 (0)