forked from googlearchive/flashlight
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamicPathMonitor.js
50 lines (46 loc) · 1.54 KB
/
DynamicPathMonitor.js
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
function DynamicPathMonitor(ref, factory) {
this.factory = factory;
this.paths = {}; // store instance of monitor, so we can unset it if the value changes
ref.on('child_added', this._add.bind(this));
ref.on('child_changed', this._change.bind(this));
ref.on('child_removed', this._remove.bind(this));
}
DynamicPathMonitor.prototype = {
_add: function(snap) {
var name = snap.name();
var pathProps = snap.val();
if ( isValidPath(pathProps) ) {
this.paths[name] = this.factory(pathProps);
console.log('Monitoring dynamic index'.green, name, pathProps);
}
},
_remove: function(snap) {
var name = snap.name();
var pathProps = snap.val();
// kill old monitor
if (this.paths[name]) {
this.paths[name]._stop();
this.paths[name] = null;
console.log('Stopped monitoring dynamic index'.red, name, pathProps);
}
},
_change: function(snap) {
var name = snap.name();
var pathProps = snap.val();
// kill old monitor
if (this.paths[name]) {
this.paths[name]._stop();
this.paths[name] = null;
console.log('Stopped monitoring dynamic index'.red, name, pathProps);
}
// create new monitor
if ( pathProps !== null && pathProps.index && pathProps.path && pathProps.type ) {
this.paths[name] = this.factory(pathProps);
console.log('Monitoring dynamic index'.green, name, pathProps);
}
}
};
function isValidPath(props) {
return props && typeof(props) === 'object' && props.index && props.path && props.type;
}
module.exports = DynamicPathMonitor;