This repository was archived by the owner on Mar 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 624
Expand file tree
/
Copy pathFirebaseObject.js
More file actions
503 lines (458 loc) · 17.7 KB
/
FirebaseObject.js
File metadata and controls
503 lines (458 loc) · 17.7 KB
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
(function() {
'use strict';
/**
* Creates and maintains a synchronized object, with 2-way bindings between Angular and Firebase.
*
* Implementations of this class are contracted to provide the following internal methods,
* which are used by the synchronization process and 3-way bindings:
* $$updated - called whenever a change occurs (a value event from Firebase)
* $$error - called when listeners are canceled due to a security error
* $$notify - called to update $watch listeners and trigger updates to 3-way bindings
* $ref - called to obtain the underlying Firebase reference
*
* Instead of directly modifying this class, one should generally use the $extend
* method to add or change how methods behave:
*
* <pre><code>
* var ExtendedObject = $firebaseObject.$extend({
* // add a new method to the prototype
* foo: function() { return 'bar'; },
* });
*
* var obj = new ExtendedObject(ref);
* </code></pre>
*/
angular.module('firebase.database').factory('$firebaseObject', [
'$parse', '$firebaseUtils', '$log', '$q',
function($parse, $firebaseUtils, $log, $q) {
/**
* Creates a synchronized object with 2-way bindings between Angular and Firebase.
*
* @param {Firebase} ref
* @returns {FirebaseObject}
* @constructor
*/
function FirebaseObject(ref) {
if( !(this instanceof FirebaseObject) ) {
return new FirebaseObject(ref);
}
var self = this;
// These are private config props and functions used internally
// they are collected here to reduce clutter in console.log and forEach
this.$$conf = {
// synchronizes data to Firebase
sync: new ObjectSyncManager(this, ref),
// stores the Firebase ref
ref: ref,
// synchronizes $scope variables with this object
binding: new ThreeWayBinding(this),
// stores observers registered with $watch
listeners: []
};
// this bit of magic makes $$conf non-enumerable and non-configurable
// and non-writable (its properties are still writable but the ref cannot be replaced)
// we redundantly assign it above so the IDE can relax
Object.defineProperty(this, '$$conf', {
value: this.$$conf
});
this.$id = ref.ref.key;
this.$priority = null;
$firebaseUtils.applyDefaults(this, this.$$defaults);
// start synchronizing data with Firebase
this.$$conf.sync.init();
// $resolved provides quick access to the current state of the $loaded() promise.
// This is useful in data-binding when needing to delay the rendering or visibilty
// of the data until is has been loaded from firebase.
this.$resolved = false;
this.$loaded().finally(function() {
self.$resolved = true;
});
}
FirebaseObject.prototype = {
/**
* Saves all data on the FirebaseObject back to Firebase.
* @returns a promise which will resolve after the save is completed.
*/
$save: function () {
var self = this;
var ref = self.$ref();
var def = $q.defer();
var dataJSON;
try {
dataJSON = $firebaseUtils.toJSON(self);
} catch (e) {
def.reject(e);
}
if (typeof dataJSON !== 'undefined') {
$firebaseUtils.doSet(ref, dataJSON).then(function() {
self.$$notify();
def.resolve(self.$ref());
}).catch(def.reject);
}
return def.promise;
},
/**
* Removes all keys from the FirebaseObject and also removes
* the remote data from the server.
*
* @returns a promise which will resolve after the op completes
*/
$remove: function() {
var self = this;
$firebaseUtils.trimKeys(self, {});
self.$value = null;
return $firebaseUtils.doRemove(self.$ref()).then(function() {
self.$$notify();
return self.$ref();
});
},
/**
* The loaded method is invoked after the initial batch of data arrives from the server.
* When this resolves, all data which existed prior to calling $asObject() is now cached
* locally in the object.
*
* As a shortcut is also possible to pass resolve/reject methods directly into this
* method just as they would be passed to .then()
*
* @param {Function} resolve
* @param {Function} reject
* @returns a promise which resolves after initial data is downloaded from Firebase
*/
$loaded: function(resolve, reject) {
var promise = this.$$conf.sync.ready();
if (arguments.length) {
// allow this method to be called just like .then
// by passing any arguments on to .then
promise = promise.then.call(promise, resolve, reject);
}
return promise;
},
/**
* @returns {Firebase} the original Firebase instance used to create this object.
*/
$ref: function () {
return this.$$conf.ref;
},
/**
* Creates a 3-way data sync between this object, the Firebase server, and a
* scope variable. This means that any changes made to the scope variable are
* pushed to Firebase, and vice versa.
*
* If scope emits a $destroy event, the binding is automatically severed. Otherwise,
* it is possible to unbind the scope variable by using the `unbind` function
* passed into the resolve method.
*
* Can only be bound to one scope variable at a time. If a second is attempted,
* the promise will be rejected with an error.
*
* @param {object} scope
* @param {string} varName
* @returns a promise which resolves to an unbind method after data is set in scope
*/
$bindTo: function (scope, varName) {
var self = this;
return self.$loaded().then(function () {
return self.$$conf.binding.bindTo(scope, varName);
});
},
/**
* Listeners passed into this method are notified whenever a new change is received
* from the server. Each invocation is sent an object containing
* <code>{ type: 'value', key: 'my_firebase_id' }</code>
*
* This method returns an unbind function that can be used to detach the listener.
*
* @param {Function} cb
* @param {Object} [context]
* @returns {Function} invoke to stop observing events
*/
$watch: function (cb, context) {
var list = this.$$conf.listeners;
list.push([cb, context]);
// an off function for cancelling the listener
return function () {
var i = list.findIndex(function (parts) {
return parts[0] === cb && parts[1] === context;
});
if (i > -1) {
list.splice(i, 1);
}
};
},
/**
* Informs $firebase to stop sending events and clears memory being used
* by this object (delete's its local content).
*/
$destroy: function(err) {
var self = this;
if (!self.$isDestroyed) {
self.$isDestroyed = true;
self.$$conf.sync.destroy(err);
self.$$conf.binding.destroy();
$firebaseUtils.each(self, function (v, k) {
delete self[k];
});
}
},
/**
* Called by $firebase whenever an item is changed at the server.
* This method must exist on any objectFactory passed into $firebase.
*
* It should return true if any changes were made, otherwise `$$notify` will
* not be invoked.
*
* @param {object} snap a Firebase snapshot
* @return {boolean} true if any changes were made.
*/
$$updated: function (snap) {
// applies new data to this object
var changed = $firebaseUtils.updateRec(this, snap);
// applies any defaults set using $$defaults
$firebaseUtils.applyDefaults(this, this.$$defaults);
// returning true here causes $$notify to be triggered
return changed;
},
/**
* Called whenever a security error or other problem causes the listeners to become
* invalid. This is generally an unrecoverable error.
* @param {Object} err which will have a `code` property and possibly a `message`
*/
$$error: function (err) {
// prints an error to the console (via Angular's logger)
$log.error(err);
// frees memory and cancels any remaining listeners
this.$destroy(err);
},
/**
* Called internally by $bindTo when data is changed in $scope.
* Should apply updates to this record but should not call
* notify().
*/
$$scopeUpdated: function(newData) {
// we use a one-directional loop to avoid feedback with 3-way bindings
// since set() is applied locally anyway, this is still performant
var def = $q.defer();
this.$ref().set($firebaseUtils.toJSON(newData), $firebaseUtils.makeNodeResolver(def));
return def.promise;
},
/**
* Updates any bound scope variables and
* notifies listeners registered with $watch
*/
$$notify: function() {
var self = this, list = this.$$conf.listeners.slice();
// be sure to do this after setting up data and init state
angular.forEach(list, function (parts) {
parts[0].call(parts[1], {event: 'value', key: self.$id});
});
},
/**
* Overrides how Angular.forEach iterates records on this object so that only
* fields stored in Firebase are part of the iteration. To include meta fields like
* $id and $priority in the iteration, utilize for(key in obj) instead.
*/
forEach: function(iterator, context) {
return $firebaseUtils.each(this, iterator, context);
}
};
/**
* This method allows FirebaseObject to be copied into a new factory. Methods passed into this
* function will be added onto the object's prototype. They can override existing methods as
* well.
*
* In addition to passing additional methods, it is also possible to pass in a class function.
* The prototype on that class function will be preserved, and it will inherit from
* FirebaseObject. It's also possible to do both, passing a class to inherit and additional
* methods to add onto the prototype.
*
* Once a factory is obtained by this method, it can be passed into $firebase as the
* `objectFactory` parameter:
*
* <pre><code>
* var MyFactory = $firebaseObject.$extend({
* // add a method onto the prototype that prints a greeting
* getGreeting: function() {
* return 'Hello ' + this.first_name + ' ' + this.last_name + '!';
* }
* });
*
* // use our new factory in place of $firebaseObject
* var obj = $firebase(ref, {objectFactory: MyFactory}).$asObject();
* </code></pre>
*
* @param {Function} [ChildClass] a child class which should inherit FirebaseObject
* @param {Object} [methods] a list of functions to add onto the prototype
* @returns {Function} a new factory suitable for use with $firebase
*/
FirebaseObject.$extend = function(ChildClass, methods) {
if( arguments.length === 1 && angular.isObject(ChildClass) ) {
methods = ChildClass;
ChildClass = function(ref) {
if( !(this instanceof ChildClass) ) {
return new ChildClass(ref);
}
FirebaseObject.apply(this, arguments);
};
}
return $firebaseUtils.inherit(ChildClass, FirebaseObject, methods);
};
/**
* Creates a three-way data binding on a scope variable.
*
* @param {FirebaseObject} rec
* @returns {*}
* @constructor
*/
function ThreeWayBinding(rec) {
this.subs = [];
this.scope = null;
this.key = null;
this.rec = rec;
}
ThreeWayBinding.prototype = {
assertNotBound: function(varName) {
if( this.scope ) {
var msg = 'Cannot bind to ' + varName + ' because this instance is already bound to ' +
this.key + '; one binding per instance ' +
'(call unbind method or create another FirebaseObject instance)';
$log.error(msg);
return $q.reject(msg);
}
},
bindTo: function(scope, varName) {
function _bind(self) {
var sending = false;
var parsed = $parse(varName);
var rec = self.rec;
self.scope = scope;
self.varName = varName;
function equals(scopeValue) {
return angular.equals(scopeValue, rec) &&
scopeValue.$priority === rec.$priority &&
scopeValue.$value === rec.$value;
}
function setScope(rec) {
parsed.assign(scope, $firebaseUtils.scopeData(rec));
}
var send = $firebaseUtils.debounce(function(val) {
var scopeData = $firebaseUtils.scopeData(val);
rec.$$scopeUpdated(scopeData)
['finally'](function() {
sending = false;
if(!scopeData.hasOwnProperty('$value')){
delete rec.$value;
delete parsed(scope).$value;
}
setScope(rec);
}
);
}, 50, 500);
var scopeUpdated = function(newVal) {
newVal = newVal[0];
if( !equals(newVal) ) {
sending = true;
send(newVal);
}
};
var recUpdated = function() {
if( !sending && !equals(parsed(scope)) ) {
setScope(rec);
}
};
// $watch will not check any vars prefixed with $, so we
// manually check $priority and $value using this method
function watchExp(){
var obj = parsed(scope);
return [obj, obj.$priority, obj.$value];
}
setScope(rec);
self.subs.push(scope.$on('$destroy', self.unbind.bind(self)));
// monitor scope for any changes
self.subs.push(scope.$watch(watchExp, scopeUpdated, true));
// monitor the object for changes
self.subs.push(rec.$watch(recUpdated));
return self.unbind.bind(self);
}
return this.assertNotBound(varName) || _bind(this);
},
unbind: function() {
if( this.scope ) {
angular.forEach(this.subs, function(unbind) {
unbind();
});
this.subs = [];
this.scope = null;
this.key = null;
}
},
destroy: function() {
this.unbind();
this.rec = null;
}
};
function ObjectSyncManager(firebaseObject, ref) {
function destroy(err) {
if( !sync.isDestroyed ) {
sync.isDestroyed = true;
ref.off('value', applyUpdate);
firebaseObject = null;
initComplete(err||'destroyed');
}
}
function init() {
ref.on('value', applyUpdate, error);
ref.once('value', function(snap) {
if (angular.isArray(snap.val())) {
$log.warn('Storing data using array indices in Firebase can result in unexpected behavior. See https://firebase.google.com/docs/database/web/structure-data for more information. Also note that you probably wanted $firebaseArray and not $firebaseObject.');
}
initComplete(null);
}, initComplete);
}
// call initComplete(); do not call this directly
function _initComplete(err) {
if( !isResolved ) {
isResolved = true;
if( err ) { def.reject(err); }
else { def.resolve(firebaseObject); }
}
}
var isResolved = false;
var def = $q.defer();
var applyUpdate = $firebaseUtils.batch(function(snap) {
if (firebaseObject) {
var changed = firebaseObject.$$updated(snap);
if( changed ) {
// notifies $watch listeners and
// updates $scope if bound to a variable
firebaseObject.$$notify();
}
}
});
var error = $firebaseUtils.batch(function(err) {
_initComplete(err);
if( firebaseObject ) {
firebaseObject.$$error(err);
}
});
var initComplete = $firebaseUtils.batch(_initComplete);
var sync = {
isDestroyed: false,
destroy: destroy,
init: init,
ready: function() { return def.promise; }
};
return sync;
}
return FirebaseObject;
}
]);
/** @deprecated */
angular.module('firebase').factory('$FirebaseObject', ['$log', '$firebaseObject',
function($log, $firebaseObject) {
return function() {
$log.warn('$FirebaseObject has been renamed. Use $firebaseObject instead.');
return $firebaseObject.apply(null, arguments);
};
}
]);
})();