-
Notifications
You must be signed in to change notification settings - Fork 6.7k
/
observe-content.ts
100 lines (86 loc) · 2.54 KB
/
observe-content.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
Directive,
ElementRef,
NgModule,
Output,
Input,
EventEmitter,
OnDestroy,
AfterContentInit,
Injectable,
NgZone,
} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {RxChain, debounceTime} from '@angular/cdk/rxjs';
/**
* Factory that creates a new MutationObserver and allows us to stub it out in unit tests.
* @docs-private
*/
@Injectable()
export class MdMutationObserverFactory {
create(callback): MutationObserver | null {
return typeof MutationObserver === 'undefined' ? null : new MutationObserver(callback);
}
}
/**
* Directive that triggers a callback whenever the content of
* its associated element has changed.
*/
@Directive({
selector: '[cdkObserveContent]'
})
export class ObserveContent implements AfterContentInit, OnDestroy {
private _observer: MutationObserver | null;
/** Event emitted for each change in the element's content. */
@Output('cdkObserveContent') event = new EventEmitter<MutationRecord[]>();
/** Used for debouncing the emitted values to the observeContent event. */
private _debouncer = new Subject<MutationRecord[]>();
/** Debounce interval for emitting the changes. */
@Input() debounce: number;
constructor(
private _mutationObserverFactory: MdMutationObserverFactory,
private _elementRef: ElementRef,
private _ngZone: NgZone) { }
ngAfterContentInit() {
if (this.debounce > 0) {
this._ngZone.runOutsideAngular(() => {
RxChain.from(this._debouncer)
.call(debounceTime, this.debounce)
.subscribe((mutations: MutationRecord[]) => this.event.emit(mutations));
});
} else {
this._debouncer.subscribe(mutations => this.event.emit(mutations));
}
this._observer = this._ngZone.runOutsideAngular(() => {
return this._mutationObserverFactory.create((mutations: MutationRecord[]) => {
this._debouncer.next(mutations);
});
});
if (this._observer) {
this._observer.observe(this._elementRef.nativeElement, {
characterData: true,
childList: true,
subtree: true
});
}
}
ngOnDestroy() {
if (this._observer) {
this._observer.disconnect();
}
this._debouncer.complete();
}
}
@NgModule({
exports: [ObserveContent],
declarations: [ObserveContent],
providers: [MdMutationObserverFactory]
})
export class ObserversModule {}