forked from googlearchive/firebase-element
-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebase-element.html
520 lines (491 loc) · 16.1 KB
/
firebase-element.html
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
<!--
@license
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="firebase-import.html">
<link rel="import" href="../polymer/polymer.html">
<!--
Element wrapper for the Firebase Web API (http://firebase.com).
`firebase-element` maps a firebase location to a `data` property.
<firebase-element id="base" location="https://YOUR.firebaseio.com/" data="{{data}}" keys="{{keys}}"></firebase-element>
<h3>My Firebase Data</h3>
<template repeat="{{key in keys}}">
<p>{{key}}: {{data[key]}}</p>
</template>
## Data Persistence
- changes that occur on the remote data are automatically reflected back into
the client-side data.
- assignments to the `data` property, or modifications to `data`'s **own** properties, are
automatically persisted back to the Firebase store.
- changes to **sub-properties** of `data` are not generally observable and are **not**
automatically persisted.
- properties bound to the `data` property work just like `data` itself (all Polymer
bindings are like this).
Examples:
// assume `this.data` is bound to the firebase-element data as shown above
resetData: function() {
// setting the data object directly will automatically also
// set the firebase location
this.data = {
name: 'anonymous',
info: 'none',
more: {
color: "yellow"
}
};
},
updateInfo: function(info) {
// setting top-level properties of the data object
// will automatically update the database
// this works via binding also
this.data.info = info;
},
updateColor: function(color) {
// changes to deep properties of the data object
// are not observed automatically, and must be
// commited to update the database
this.data.more.color = color;
// in this case, we use `commitProperty` to commit
// the top-level property that has deep changes
this.$.base.commitProperty('more');
}
## Observing Changes
Whenever `firebase-element` detects a change in data, from either client or server side, it
bubbles a `data-change` event. `data-change` events are frequency-limited (throttled).
Changes in data objects are also observable directly, but you must observe relevant properties
directly. Changes in sub-properties are not automatically observed, following normal Polymer rules.
Examples:
observe: {
// dataChanged only called if data is pointed at a new object
// changes to data's _properties or sub-properites are not observed_
data: 'dataChanged',
// dataNameChanged called if `data.name` changes
'data.name': 'dataNameChanged'
}
## Arrays and Objects
Firebase stores all data as Objects, even Arrays are stored as objects with numerical keys.
As a convenience, the Firebase Web API automatically converts Array-like Objects into Arrays
for use JavaScript.
Arrays are generally inconvenient for large data-storage. For example, if you delete an
element from an array, all the subsequent elements need their indices (keys) updated.
To support lists of data without using Arrays, Firebase supports a `push` method which
adds an entry to an Object using a string key instead of an index.
addEntry: function(value) {
this.$.base.push({foo: value});
}
## Child Events
Firebase supports notifications when properties on `data` are removed, added, or modified.
Any of these changes will cause firebase-element to fire `data-change` method as described
above. However, you can also listen for discrete child events, by setting `childEvents`
property to true. The events are `child-added`, `child-moved` `child-removed`, and `child-changed`. Each
`event` object has a `detail` property with `name` and `value` properties identifying the
modified item.
Example:
<firebase-element childEvents on-child-added="{{childAdded}}" ...>
...
childAdded: function(event) {
console.log('added ', event.detail.name, ':', event.detail.value);
}
@class firebase-element
@blurb Element wrapper for the Firebase Web API (http://firebase.com).
@status alpha
@snap snap.png
-->
<polymer-element name="firebase-element">
<script>
/*
note: switching between Array and Object datatypes will mess up
live firebase-element elements
*/
Polymer('firebase-element', {
publish: {
/**
* Fired when properties on `data` are added, removed, or modified.
*
* @event data-change
*/
/**
* Fired when an error occurs on an interaction with Firebase. The
* `details.error` property contains the `Error` object provided by
* the Firebase API.
*
* @event error
*/
/**
* Firebase location mapped to `data`.
* @attribute location
* @type String
*/
location: null,
/**
* Firebase `ref` object corresponding to `location`.
* @attribute ref
* @type Object
*/
ref: null,
/**
* Restricts the number of records reflected on the client.
* This method is deprecated. Use limitToFirst() and limitToLast() instead.
* @attribute limit
* @type Number
*/
limit: 0,
/**
* Specify a maximum number of records reflected on the client limited to the first certain number of children.
* @attribute limitToFirst
* @type Number
*/
limitToFirst: 0,
/**
* Specify a maximum number of records reflected on the client limited to the last certain number of children.
* @attribute limitToLast
* @type Number
*/
limitToLast: 0,
/**
* Specify an start record for the set of records reflected on the client.
* @attribute start
* @type Any
*/
start: null,
/**
* Specify an ending record for the set of records reflected on the client.
* @attribute end
* @type Any
*/
end: null,
/**
* Specify a child key to order the set of records reflected on the client.
* @attribute orderByChild
* @type Any
*/
orderByChild: null,
/**
* Specify to order by key the set of records reflected on the client.
* @attribute orderByKey
* @type Any
*/
orderByKey: null,
/**
* Specify to order by priority the set of records reflected on the client.
* @attribute orderByPriority
* @type Any
*/
orderByPriority: null,
/**
* Specify to create a query which includes children which match the specified value. The argument type depends on which orderBy*() function was used in this query. Specify a value that matches the orderBy*() type.
* @attribute equalTo
* @type Any
*/
equalTo: null,
/**
* The `data` object mapped to `location`.
* @attribute data
* @type Object
*/
data: null,
/**
* All keys in data (array of names, if you think of data as a set of name/value pairs).
* @attribute keys
* @type Array
*/
keys: null,
/**
* If true, will fire `child-added`,`child-moved` `child-removed`, `child-changed` events.
* @attribute childEvents
* @type Boolean
*/
childEvents: false,
/**
* When set, data will be stored with the given Firebase priority level.
* @attribute priority
* @type Number
*/
priority: null,
/**
* Reflects whether the data at this locaation as been read at least once
* @attribute initialized
* @type Boolean
*/
dataReady: false,
/**
* If true, will log various occurances to the console api.
* @attribute log
* @type Boolean
*/
log: false
},
observe: {
'ref limit start end limitToFirst limitToLast equalTo': 'requery'
},
locationChanged: function() {
// shut-down previous observers (if any)
this.closeQuery();
this.closeObserver();
// connect to db
if (this.location) {
this.ref = new Firebase(this.location);
} else {
this.ref = null;
}
},
requery: function() {
// shut-down previous observers (if any)
this.closeQuery();
this.closeObserver();
// construct new query
var query = this.ref;
if (query) {
if (this.start) {
query = query.startAt(this.start);
}
if (this.end) {
query = query.endAt(this.end);
}
if (this.limit > 0) {
console.log('limit method is deprecated as firebase 2.0.0. Use limitToFirst() and limitToLast() instead.');
query = query.limit(this.limit);
}
if (this.limitToFirst > 0) {
query = query.limitToFirst(this.limitToFirst);
}
if (this.limitToLast > 0) {
query = query.limitToLast(this.limitToLast);
}
if (this.orderByChild) {
query = query.orderByChild(this.orderByChild);
}
if (this.orderByKey) {
query = query.orderByKey();
}
if (this.orderByPriority) {
query = query.orderByPriority();
}
if (this.equalTo) {
query = query.equalTo(this.equalTo);
}
this.query = query;
}
},
queryChanged: function() {
// initialize
this._setData(null);
// data acquisition
this.dataReady = false;
this.valueLoading = true;
this.query.once('value', this.valueLoaded, this.errorHandler, this);
// observe server-side data
this.observeQuery();
},
valueLoaded: function(snapshot) {
this.valueLoading = false;
if (this.ref.key() !== snapshot.key()) {
this.log && console.warn('squelching stale response [%s]', snapshot.key());
return;
}
this.log && console.log('acquired value ' + this.location);
this.dataReady = true;
this._setData(snapshot.val());
if (this.data) {
this.dataChange();
}
},
_setData: function(data) {
this.closeObserver();
this.data = this._data = data;
this.observeData();
},
//
// server-side data-observation
//
observeQuery: function() {
// server side dynamics
this.query.on('child_added', this.childAdded, this.errorHandler, this);
this.query.on('child_changed', this.childChanged, this.errorHandler, this);
this.query.on('child_moved', this.childMoved, this.errorHandler, this);
this.query.on('child_removed', this.childRemoved, this.errorHandler, this);
},
closeQuery: function() {
if (this.query) {
this.query.off();
}
},
//
// client-side data-observation
//
observeData: function() {
if (this.data instanceof Array) {
this.observer = new ArrayObserver(this.data);
this.observer.open(this.observeArray.bind(this));
} else if (this.data instanceof Object) {
this.observer = new ObjectObserver(this.data);
this.observer.open(this.observeObject.bind(this));
}
},
closeObserver: function() {
if (this.observer) {
this.observer.close();
this.observer = null;
}
},
dataChanged: function() {
if (this._data !== this.data) {
this._setData(this.data);
this.commit();
}
},
priorityChanged: function() {
if (this.ref && (this.priority != null)) {
this.ref.setPriority(this.priority, this.errorHandler);
}
},
discardObservations: function() {
if (this.observer) {
this.observer.discardChanges();
}
},
deliverObservations: function() {
if (this.observer) {
this.observer.deliver();
}
},
//
// server-side effects
//
childAdded: function(snapshot) {
if (this.data) {
// ignore initial adds, we'll take the 'value' instead
this.modulateData('updateData', snapshot);
} else if (!this.valueLoading) {
// if children are added to a previously null location, grab the whole value in one go
this.valueLoading = true;
this.query.once('value', this.valueLoaded, this);
}
this.childEvent('child-added', snapshot);
},
childChanged: function(snapshot) {
if (!this.valueLoading) {
this.modulateData('updateData', snapshot);
}
this.childEvent('child-changed', snapshot);
},
childMoved: function(snapshot) {
if (!this.valueLoading) {
this.modulateData('updateData', snapshot);
}
this.childEvent('child-moved', snapshot);
},
childRemoved: function(snapshot) {
if (!this.valueLoading) {
this.modulateData('removeData', snapshot);
}
this.childEvent('child-removed', snapshot);
},
childEvent: function(kind, snapshot) {
this.log && console.log(kind, snapshot.key());
if (this.childEvents) {
this.fire(kind, {name: snapshot.key(), value: snapshot.val()});
}
},
modulateData: function(operation, snapshot) {
// handle any pending observations
this.deliverObservations();
this[operation](snapshot);
this.dataChange();
// discard any observations so we don't send this value back to the
// server, it may already be stale from the server's perspective
this.discardObservations();
},
updateData: function(snapshot) {
if (!this.data) {
this.data = {};
}
this.data[snapshot.key()] = snapshot.val();
},
removeData: function(snapshot) {
var key = snapshot.key();
if (this.data instanceof Array) {
this.data.splice(key, 1);
if (this.data.length == 0) {
this._setData(null);
}
} else if (this.data) {
delete this.data[key];
if (Object.keys(this.data).length === 0) {
this._setData(null);
}
}
},
dataChange: function() {
//this.job('change', function() {
if (this.data) {
this.keys = this.data ? Object.keys(this.data) : [];
}
this.fire('data-change');
//});
},
//
// client-side effects
//
observeArray: function(splices) {
//console.warn('observeArray');
// TODO(sjmiles): arrays are nasty because simple insertions/deletions
// cause changes to ripple through keys
this.commit();
},
observeObject: function(added, removed, changed, getOldValueFn) {
// client-side dynamics
var ctrlr = this;
Object.keys(added).forEach(function(property) {
ctrlr.commitProperty(property);
});
Object.keys(removed).forEach(function(property) {
ctrlr.remove(property);
});
Object.keys(changed).forEach(function(property) {
ctrlr.commitProperty(property);
});
},
// api for manual commits
commitProperty: function(key) {
this.log && console.log('commitProperty ' + key);
if (this.ref) {
this.ref.child(key).set(this.data[key], this.errorHandler);
}
},
remove: function(key) {
this.ref.child(key).remove(this.errorHandler);
},
commit: function() {
this.log && console.log('commit');
if (this.ref) {
if (this.priority != null) {
this.ref.setWithPriority(this.data || {}, this.priority, this.errorHandler);
} else {
this.ref.set(this.data || {}, this.errorHandler);
}
}
},
push: function(item) {
var neo;
if (this.data instanceof Array) {
this.commitProperty(this.data.push(item)-1);
} else {
neo = this.ref.push(item, this.errorHandler);
}
this.dataChange();
return neo;
},
errorHandler: function(error) {
if (error) {
this.fire('error', {error: error});
}
}
});
</script>
</polymer-element>