forked from googlearchive/backbonefire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backbone-firebase.js
365 lines (318 loc) · 10.1 KB
/
backbone-firebase.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
358
359
360
361
362
363
364
365
/**
* Backbone Firebase Adapter.
*/
(function() {
var _ = this._;
var Backbone = this.Backbone;
Backbone.Firebase = function(ref) {
this._fbref = ref;
this._children = [];
if (typeof ref == "string") {
this._fbref = new Firebase(ref);
}
_.bindAll(this);
this._fbref.on("child_added", this._childAdded);
this._fbref.on("child_moved", this._childMoved);
this._fbref.on("child_changed", this._childChanged);
this._fbref.on("child_removed", this._childRemoved);
};
_.extend(Backbone.Firebase.prototype, {
_childAdded: function(childSnap, prevChild) {
var model = childSnap.val();
model.id = childSnap.name();
if (prevChild) {
var item = _.find(this._children, function(child) {
return child.id == prevChild
});
this._children.splice(this._children.indexOf(item) + 1, 0, model);
} else {
this._children.unshift(model);
}
},
_childMoved: function(childSnap, prevChild) {
var model = childSnap.val();
this._children = _.reject(this._children, function(child) {
return child.id == model.id;
});
this._childAdded(childSnap, prevChild);
},
_childChanged: function(childSnap, prevChild) {
var model = childSnap.val();
model.id = childSnap.name();
var item = _.find(this._children, function(child) {
return child.id == model.id
});
this._children[this._children.indexOf(item)] = model;
},
_childRemoved: function(oldChildSnap) {
var model = oldChildSnap.val();
this._children = _.reject(this._children, function(child) {
return child.id == model.id
});
},
create: function(model, cb) {
if (!model.id) {
model.id = this._fbref.ref().push().name();
}
var val = model.toJSON();
this._fbref.ref().child(model.id).set(val, _.bind(function(err) {
if (!err) {
cb(null, val);
} else {
cb("Could not create model " + model.id);
}
}, this));
},
read: function(model, cb) {
if (!model.id) {
_.defer(cb, "Invalid model ID provided to read");
return;
}
var index = _.find(this._children, function(child) {
return child.id == model.id
});
_.defer(cb, null, this._children[index]);
},
readAll: function(model, cb) {
_.defer(cb, null, this._children);
},
update: function(model, cb) {
var val = model.toJSON();
this._fbref.ref().child(model.id).update(val, function(err) {
if (!err) {
cb(null, val);
} else {
cb("Could not update model " + model.id, null);
}
});
},
delete: function(model, cb) {
this._fbref.ref().child(model.id).remove(function(err) {
if (!err) {
cb(null, model);
} else {
cb("Could not delete model " + model.id);
}
});
}
});
Backbone.Firebase.sync = function(method, model, options, error) {
var store = model.firebase || model.collection.firebase;
// Backwards compatibility with Backbone <= 0.3.3
if (typeof options == 'function') {
options = {
success: options,
error: error
};
}
if (method == "read" && model.id == undefined) {
method = "readAll";
}
store[method].apply(this, [model, function(err, val) {
if (err) {
model.trigger("error", model, err, options);
if (Backbone.VERSION === "0.9.10") {
options.error(model, err, options);
} else {
options.error(err);
}
} else {
model.trigger("sync", model, val, options);
if (Backbone.VERSION === "0.9.10") {
options.success(model, val, options);
} else {
options.success(val);
}
}
}]);
};
Backbone.oldSync = Backbone.sync;
// Override 'Backbone.sync' to default to Firebase sync.
// the original 'Backbone.sync' is still available in 'Backbone.oldSync'
Backbone.sync = function(method, model, options, error) {
var syncMethod = Backbone.oldSync;
if (model.firebase || (model.collection && model.collection.firebase)) {
syncMethod = Backbone.Firebase.sync;
}
return syncMethod.apply(this, [method, model, options, error]);
};
// Custom Firebase Collection.
Backbone.Firebase.Collection = Backbone.Collection.extend({
sync: function() {
this._log("Sync called on a Firebase collection, ignoring.");
},
fetch: function() {
this._log("Fetch called on a Firebase collection, ignoring.");
},
constructor: function(models, options) {
// Apply parent constructor (this will also call initialize).
Backbone.Collection.apply(this, arguments);
if (options && options.firebase) {
this.firebase = options.firebase;
}
switch (typeof this.firebase) {
case "object": break;
case "string": this.firebase = new Firebase(this.firebase); break;
case "function": this.firebase = this.firebase(); break;
default: throw new Error("Invalid firebase reference created");
}
// Add handlers for remote events.
this.firebase.on("child_added", this._childAdded.bind(this));
this.firebase.on("child_moved", this._childMoved.bind(this));
this.firebase.on("child_changed", this._childChanged.bind(this));
this.firebase.on("child_removed", this._childRemoved.bind(this));
// Add handlers for all models in this collection, and any future ones
// that may be added.
function _updateModel(model, options) {
this.firebase.ref().child(model.id).update(model.toJSON());
}
function _unUpdateModel(model) {
model.off("change", _updateModel, this);
}
for (var i = 0; i < this.models.length; i++) {
this.models[i].on("change", _updateModel, this);
this.models[i].once("remove", _unUpdateModel, this);
}
this.on("add", function(model) {
model.on("change", _updateModel, this);
model.once("remove", _unUpdateModel, this);
}, this);
},
comparator: function(model) {
return model.id;
},
add: function(models, options) {
var parsed = this._parseModels(models);
for (var i = 0; i < parsed.length; i++) {
var model = parsed[i];
this.firebase.ref().child(model.id).set(model);
}
// TODO: Implement options.success
},
remove: function(models, options) {
var parsed = this._parseModels(models);
for (var i = 0; i < parsed.length; i++) {
var model = parsed[i];
this.firebase.ref().child(model.id).set(null);
}
// TODO: Implement options.success
},
create: function(model, options) {
this._log("Create called, aliasing to add. Consider using Collection.add!");
options = options ? _.clone(options) : {};
if (options.wait) {
this._log("Wait option provided to create, ignoring.");
}
model = Backbone.Collection.prototype._prepareModel.apply(
this, [model, options]
);
if (!model) {
return false;
}
this.add([model], options);
return model;
},
_log: function(msg) {
if (console && console.log) {
console.log(msg);
}
},
// TODO: Options will be ignored for add & remove, document this!
_parseModels: function(models) {
var ret = [];
models = _.isArray(models) ? models.slice() : [models];
for (var i = 0; i < models.length; i++) {
var model = models[i];
if (model.toJSON && typeof model.toJSON == "function") {
model = model.toJSON();
}
if (!model.id) {
model.id = this.firebase.ref().push().name();
}
ret.push(model);
}
return ret;
},
_childAdded: function(snap) {
Backbone.Collection.prototype.add.apply(this, [snap.val()]);
},
_childMoved: function(snap) {
// TODO: Investigate: can this occur without the ID changing?
this._log("_childMoved called with " + snap.val());
},
_childChanged: function(snap) {
var model = snap.val();
var item = _.find(this.models, function(child) {
return child.id == model.id
});
if (!item) {
// TODO: Investigate: what is the right way to handle this case?
throw new Error("Could not find model with ID " + model.id);
}
item.set(model);
},
_childRemoved: function(snap) {
Backbone.Collection.prototype.remove.apply(this, [snap.val()]);
}
});
// Custom Firebase Model.
Backbone.Firebase.Model = Backbone.Model.extend({
save: function() {
this._log("Save called on a Firebase model, ignoring.");
},
destroy: function(options) {
// TODO: Fix naive success callback. Add error callback.
this.firebase.ref().set(null, this._log);
this.trigger('destroy', this, this.collection, options);
if (options.success) {
options.success(this,null,options);
}
},
constructor: function(model, options) {
// Apply parent constructor (this will also call initialize).
Backbone.Model.apply(this, arguments);
if (options && options.firebase) {
this.firebase = options.firebase;
}
switch (typeof this.firebase) {
case "object": break;
case "string": this.firebase = new Firebase(this.firebase); break;
case "function": this.firebase = this.firebase(); break;
default: throw new Error("Invalid firebase reference created");
}
// Add handlers for remote events.
this.firebase.on("value", this._modelChanged.bind(this));
this.on("change", this._updateModel, this);
},
_updateModel: function(model, options) {
// Find the deleted keys and set their values to null
// so Firebase properly deletes them.
var modelObj = model.toJSON();
_.each(model.changed, function(value, key) {
if (typeof value === "undefined" || value === null)
modelObj[key] = null;
});
this.firebase.ref().update(modelObj, this._log);
},
_modelChanged: function(snap) {
// Unset attributes that have been deleted from the server
// by comparing the keys that have been removed.
var newModel = snap.val();
if (typeof newModel === "object" && newModel !== null) {
var diff = _.difference(_.keys(this.attributes), _.keys(newModel));
var _this = this;
_.each(diff, function(key) {
_this.unset(key);
});
}
this.set(newModel);
this.trigger('sync', this, null, null);
},
_log: function(msg) {
if (typeof msg === "undefined" || msg === null) return;
if (console && console.log) {
console.log(msg);
}
}
});
})();