-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathAngularFire.js
113 lines (90 loc) · 2.15 KB
/
AngularFire.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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
import Firebase from 'firebase/firebase';
export class AngularFire {
ref: Firebase;
constructor(ref: Firebase) {
this.ref = ref;
}
asArray() {
return new FirebaseArray(this.ref);
}
}
/*
FirebaseArray
*/
export class FirebaseArray {
ref: Firebase;
error: any;
list: Array;
constructor(ref: Firebase) {
this.ref = ref;
this.list = [];
// listen for changes at the Firebase instance
this.ref.on('child_added', this.created.bind(this), this.error);
this.ref.on('child_moved', this.moved.bind(this), this.error);
this.ref.on('child_changed', this.updated.bind(this), this.error);
this.ref.on('child_removed', this.removed.bind(this), this.error);
// determine when initial load is completed
// ref.once('value', function() { resolve(null); }, resolve);
}
getItem(recOrIndex: any) {
var item = recOrIndex;
if(typeof(recOrIndex) === "number") {
item = this.getRecord(recOrIndex);
}
return item;
}
getChild(recOrIndex: any) {
var item = this.getItem(recOrIndex);
return this.ref.child(item._key);
}
add(rec: any) {
this.ref.push(rec);
}
remove(recOrIndex: any) {
this.getChild(recOrIndex).remove();
}
save(recOrIndex: any) {
var item = this.getItem(recOrIndex);
this.getChild(recOrIndex).update(item);
}
keyify(snap) {
var item = snap.val();
item._key = snap.key();
return item;
}
created(snap) {
debugger;
var addedValue = this.keyify(snap);
this.list.push(addedValue);
}
moved(snap) {
var key = snap.key();
this.spliceOut(key);
}
updated(snap) {
var key = snap.key();
var indexToUpdate = this.indexFor(key);
this.list[indexToUpdate] = this.keyify(snap);
}
removed(snap) {
var key = snap.key();
this.spliceOut(key);
}
bulkUpdate(items) {
this.ref.update(items);
}
spliceOut(key) {
var i = this.indexFor(key);
if( i > -1 ) {
return this.list.splice(i, 1)[0];
}
return null;
}
indexFor(key) {
var record = this.getRecord(key);
return this.list.indexOf(record);
}
getRecord(key) {
return this.list.find((item) => key === item._key);
}
}