-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
61 lines (52 loc) · 1.57 KB
/
index.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
51
52
53
54
55
56
57
58
59
60
61
var Firebase = require('client-firebase');
var DEFAULT_FIREBASE_ROOT = null;
var MultiplayerMixin = {
componentWillMount: function() {
this.updatingFromFirebase = false;
var firebaseURL = null;
if (this.getFirebaseURL) {
firebaseURL = this.getFirebaseURL();
} else if (DEFAULT_FIREBASE_ROOT) {
firebaseURL = DEFAULT_FIREBASE_ROOT;
if (firebaseURL[firebaseURL.length - 1] !== '/') {
firebaseURL += '/';
}
firebaseURL += window.btoa(this._rootNodeID + ',' + this._mountDepth);
} else {
throw new Error('Must either call setFirebaseRoot() or provide a getFirebaseURL() method');
}
this.firebase = new Firebase(firebaseURL);
},
componentDidMount: function() {
this.firebase.on('value', this.handleFirebaseValue);
},
componentWillUnmount: function() {
this.firebase.off('value', this.handleFirebaseValue);
},
componentDidUpdate: function(prevProps, prevState) {
if (this.updatingFromFirebase) {
return;
}
var update = {};
for (var k in this.state) {
if (prevState[k] !== this.state[k]) {
update[k] = this.state[k];
}
}
this.firebase.update(update);
},
handleFirebaseDone: function() {
this.updatingFromFirebase = false;
},
handleFirebaseValue: function(snapshot) {
this.updatingFromFirebase = true;
// TODO: can we remove this double reconcile?
this.replaceState(snapshot.val(), this.handleFirebaseDone);
}
};
module.exports = {
Mixin: MultiplayerMixin,
setFirebaseRoot: function(root) {
DEFAULT_FIREBASE_ROOT = root;
}
};