@@ -7,11 +7,22 @@ import {
7
7
EventEmitter ,
8
8
OnDestroy ,
9
9
AfterContentInit ,
10
- Injector ,
10
+ Injectable ,
11
11
} from '@angular/core' ;
12
12
import { Subject } from 'rxjs/Subject' ;
13
13
import 'rxjs/add/operator/debounceTime' ;
14
14
15
+ /**
16
+ * Factory that creates a new MutationObserver and allows us to stub it out in unit tests.
17
+ * @docs -private
18
+ */
19
+ @Injectable ( )
20
+ export class MdMutationObserverFactory {
21
+ create ( callback ) : MutationObserver {
22
+ return new MutationObserver ( callback ) ;
23
+ }
24
+ }
25
+
15
26
/**
16
27
* Directive that triggers a callback whenever the content of
17
28
* its associated element has changed.
@@ -31,15 +42,22 @@ export class ObserveContent implements AfterContentInit, OnDestroy {
31
42
/** Debounce interval for emitting the changes. */
32
43
@Input ( ) debounce : number ;
33
44
34
- constructor ( private _elementRef : ElementRef , private _injector : Injector ) { }
45
+ constructor (
46
+ private _mutationObserverFactory : MdMutationObserverFactory ,
47
+ private _elementRef : ElementRef ) { }
35
48
36
49
ngAfterContentInit ( ) {
37
- this . _debouncer
38
- . debounceTime ( this . debounce )
39
- . subscribe ( mutations => this . event . emit ( mutations ) ) ;
50
+ if ( this . debounce > 0 ) {
51
+ this . _debouncer
52
+ . debounceTime ( this . debounce )
53
+ . subscribe ( mutations => this . event . emit ( mutations ) ) ;
54
+ } else {
55
+ this . _debouncer . subscribe ( mutations => this . event . emit ( mutations ) ) ;
56
+ }
40
57
41
- this . _observer = new ( this . _injector . get ( MutationObserver ) as any ) (
42
- ( mutations : MutationRecord [ ] ) => this . _debouncer . next ( mutations ) ) ;
58
+ this . _observer = this . _mutationObserverFactory . create ( ( mutations : MutationRecord [ ] ) => {
59
+ this . _debouncer . next ( mutations ) ;
60
+ } ) ;
43
61
44
62
this . _observer . observe ( this . _elementRef . nativeElement , {
45
63
characterData : true ,
@@ -51,17 +69,16 @@ export class ObserveContent implements AfterContentInit, OnDestroy {
51
69
ngOnDestroy ( ) {
52
70
if ( this . _observer ) {
53
71
this . _observer . disconnect ( ) ;
54
- this . _observer = null ;
72
+ this . _debouncer . complete ( ) ;
73
+ this . _debouncer = this . _observer = null ;
55
74
}
56
75
}
57
76
}
58
77
78
+
59
79
@NgModule ( {
60
80
exports : [ ObserveContent ] ,
61
81
declarations : [ ObserveContent ] ,
62
- providers : [
63
- // Pass the MutationObserver through DI so it can be stubbed when testing.
64
- { provide : MutationObserver , useValue : MutationObserver }
65
- ]
82
+ providers : [ MdMutationObserverFactory ]
66
83
} )
67
84
export class ObserveContentModule { }
0 commit comments