This repository has been archived by the owner on May 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebind.js
357 lines (302 loc) · 13.8 KB
/
firebind.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
//FireBind v0.5.1, by Tyrsius
(function(ko) {
var convertToSimpleJS = function(model) {
var result= JSON.parse(ko.toJSON(model));
return result;
};
var getItemById = function(items, idProperty, id) {
var setItem;
for (var i = 0; i < items.length; i++) {
if (items[i][idProperty] === id) {
setItem = items[i];
break;
};
}
return setItem;
};
var removeFireSetItem = function(fireSet, childId) {
var item = fireSet.child(childId);
if (item != null)
item.remove();
return item;
};
var isNumber = function(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
/*
A fire set is an observableArray of a firebase location
If you do not specify a config.id property to serve as the
'name' of the firebase child, 'id' will be used by default.
All sets use firebase priority, to ensure consistent behavior
By default, an int priority will be generated for each new item
In the set. All methods that would modify the order
will take this priority into account. Optionally, you can
specify a property of the children to use as the prioirity
by setting config.orderBy.
*/
ko.fireSet = function(fireSet, Constructor, config) {
var set = ko.observableArray(),
config = config || {},
idProperty = config.id || 'id',
priorityProperty = config.orderBy, //undefined is fine
priorityMap = {};
//------------------------------------------
//-------------Firebase Events--------------
//------------------------------------------
//Keep a reference to the original set methods
var setPush = set.push,
setRemove = set.remove,
setSplice = set.splice,
setUnshift = set.unshift;
fireSet.on('child_added', function(item, prevItemId) {
var id = item.name(),
data = item.val(),
child = new Constructor(id, data, fireSet.child(id));
//Set the priorty of the item in the map
priorityMap[id] = item.getPriority();
//If no previous child is given, just add it to the end
if (prevItemId === undefined)
setPush.call(set, child);
//If previous child is given, but null, ordering is on
//but this item is the first, so add it to the beginning
else if (prevItemId === null)
setUnshift.call(set, child);
//Otherwise, find the correct index to put it in
else {
var items = set(),
prevItem = getItemById(items, idProperty, prevItemId),
prevItemIndex = items.indexOf(prevItem);;
setSplice.call(set, prevItemIndex + 1, 0, child);
}
});
fireSet.on('child_moved', function(item, prevItemId) {
var id = item.name()
items = set.peek()
setItem = getItemById(items, idProperty, id),
oldIndex = items.indexOf(setItem),
newIndex = 0;
//Set the priorty of the item in the map
priorityMap[id] = item.getPriority();
var oldItem = setSplice.call(set, oldIndex, 1)[0];
//Only try to find the new index if a previous child was given
//Otherwise the item has been moved to the front
if (prevItemId !== null) {
var prevSetItem = getItemById(items, idProperty, prevItemId),
newIndex = items.indexOf(prevSetItem) + 1;
}
setSplice.call(set, newIndex, 0, oldItem);
});
fireSet.on('child_removed', function(item) {
var id = item.name(),
items = set(),
setItem = getItemById(items, idProperty, id);
//Remove the priority from the map
delete priorityMap[id];
setRemove.call(set, setItem);
});
//----------------------------------------
//---------------Set Methods--------------
//----------------------------------------
/*
We don't modify the Set() here, we allow the firebase events to
do that so that it only happens in a single place. Doing so
ensure that security is always enforced, and that ordering is
handled properly. We replace all the array modifying methods
with ones that just call the proper firebase methods.
*/
set.push = function() {
var args = Array.prototype.slice.call(arguments),
items = set.peek();
//Determine if we are sorting by default, or based on a property
//If we are, we don't need to bother trying to add to the beginning or end
if (priorityProperty) {
args.forEach(function(item) {
fireSet.push().setWithPriority(convertToSimpleJS(item), ko.unwrap(item[priorityProperty]));
});
} else {
var newPriority = 0;
//if there are any items
if (items.length) {
var lastSetItem = items[items.length - 1];
newPriority = priorityMap[ko.unwrap(lastSetItem[idProperty])];
//Round up to normalize numbers that may have become very precise floats
//Check numeracy to ensure sanity
newPriority = isNumber(newPriority) ? Math.ceil(newPriority) : 0;
}
args.forEach(function(item) {
newPriority++;
fireSet.push().setWithPriority(convertToSimpleJS(item), newPriority);
});
}
//Just assume everything will add correctly
return items.length + arguments.length;
};
set.pop = function(){
var items = set.peek(),
item = items[items.length - 1];
removeFireSetItem(fireSet, ko.unwrap(item[idProperty]));
return item;
};
set.shift = function() {
var item = set.peek()[0];
removeFireSetItem(fireSet, ko.unwrap(item[idProperty]));
return item;
};
set.unshift = function() {
var items = set.peek(),
itemsToAdd = Array.prototype.slice.call(arguments);
//Determine if we are sorting by default, or based on a property
//If we are, we don't need to bother trying to add to the beginning or end
if (priorityProperty) {
itemsToAdd.forEach(function(item) {
fireSet.push().setWithPriority(convertToSimpleJS(item), ko.unwrap(item[priorityProperty]));
});
} else {
if (items.length) { //Items already present
var sliceItem = items[0],
slicePriority = priorityMap[ko.unwrap(sliceItem[idProperty])],
newPriority = slicePriority / 2;
itemsToAdd.forEach(function(item) {
fireSet.push().setWithPriority(convertToSimpleJS(item), newPriority);
//Get priority inbetween previous and original priority
newPriority = (newPriority + slicePriority) / 2;
});
} else { //No items present, just add everything
var newPriority = 0;
itemsToAdd.forEach(function(item) {
newPriority++;
fireSet.push().setWithPriority(convertToSimpleJS(item), newPriority);
});
}
}
//Just assume everything will add correctly
return items.length + arguments.length;
};
set.remove = function(valueOrPredicate) {
var items = set.peek(),
removedValues = [];
var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate)
? valueOrPredicate
: function (value) { return value === valueOrPredicate; };
items.forEach(function(item) {
if (predicate(item)) {
removeFireSetItem(fireSet, item[idProperty]);
removedValues.push(item);
}
});
return removedValues;
};
set.removeAll = function(arrayOfValues) {
//If you passed nothing, we should remove everything
if (arrayOfValues === undefined) {
fireSet.remove();
return set().slice(0);
} else {
return set.remove(function(value) {
return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
});
}
};
set.sort = function(sorter) {
//Calling this method when priorityProperty doesn't really do much, so just return
if (priorityProperty && !sorter)
return set.peek();
sorter = sorter && typeof sorter === 'function' || function(left, right) {
if (sorter)
return ko.unwrap(left[sorter]) > ko.unwrap(right[sorter]) ? 1 : -1;
else
return priorityMap[ko.unwrap(left[idProperty])] > priorityMap[ko.unwrap(right[idProperty])] ? 1 : -1;
};
var items = set.peek(),
newPriority = Math.floor(priorityMap[ko.unwrap(items[0][idProperty])]),
sortItems = items.slice(0).sort(sorter);
//
sortItems.forEach(function(item) {
fireSet.child(ko.unwrap(item[idProperty])).setPriority(newPriority);
newPriority++;
});
};
set.reverse = function() {
if (priorityProperty)
throw new Error("You cannot reverse a fireSet that is sorted on a property.");
set.sort(function(left, right) {
return ko.unwrap(left[sorter]) > ko.unwrap(right[sorter]) ? -1 : 1;
});
};
set.move = function(oldIndex, newIndex) {
var items = set.peek(),
item = items[oldIndex],
l = items.length,
fireChild = fireSet.child(ko.unwrap(item[idProperty])),
up = oldIndex > newIndex;
if (priorityProperty)
throw new Error("You cannot move a fireSet that is sorted on a property.");
//Obviously, you can't move things with less than two items
if (l < 2)
return;
//Negatives are offsets
//Use mod to allow for negatives larger than the array to wrap around
//The extra mod is to handle the case where % index == l, since that is
//Actually outside the array bound, when it should be 0
if (newIndex < 0)
newIndex = ((newIndex) % l + l) % l;
//Values larger than the array will wrap around to the beginning
else if (newIndex >= l)
newIndex = 0;
if (newIndex === 0) {
var firstPriority = priorityMap[ko.unwrap(items[0][idProperty])];
fireChild.setPriority(Math.floor(firstPriority - 1));
} else if (newIndex === (l - 1)) {
var lastPriority = priorityMap[ko.unwrap(items[newIndex][idProperty])];
fireChild.setPriority(Math.ceil(lastPriority + 1));
} else {
var left = items[up ? newIndex - 1 : newIndex],
right = items[up ? newIndex : newIndex + 1],
leftPriority = priorityMap[ko.unwrap(left[idProperty])];
rightPriority = priorityMap[ko.unwrap(right[idProperty])],
newPriority = (leftPriority + rightPriority) / 2;
fireChild.setPriority(newPriority);
}
};
set.splice = function(index, howMany) {
throw new Error("Splice is not currently implemented. You can use move or remove.");
/*
var items = set.peek(),
itemsToAdd = Array.prototype.slice.call(arguments).slice(2), //Only get adds
removedItems = [];
if (itemsToAdd && priorityProperty)
throw new Error("You cannot splice items into a fireSet that is sorted on a property");
if (howMany) {
//If index is negative, its an offset
//We need to get howMany from the total
var end = index < 0 ? items.length - index + howMany : index + howMany
removedItems = items.slice(index, end);
set.removeAll(removedItems);
}
if (itemsToAdd.length > 0) {
addItemsToSetBeforeIndex(fireSet, priorityMap, idProperty, items, index, itemsToAdd);
}
return removedItems;
*/
};
//Slice is fine, doesn't need to change
//return the modified observable array
return set;
};
ko.fireModel = function(model, map, fireRef) {
var keys = Object.keys(map);
keys.forEach(function(property) {
var base = ko.observable(),
baseRef = fireRef.child(property);
baseRef.on('value', function(snapshot) {
base(snapshot.val());
});
model[property] = ko.computed({
read: base,
write: function(value) {
baseRef.set(value);
}
});
});
};
})(ko);