wait until firebase connects before trying to access data

This commit is contained in:
Chris Karlof 2013-10-10 18:24:49 -07:00
Родитель b31a2029ff
Коммит f6950f7c82
2 изменённых файлов: 19 добавлений и 5 удалений

Просмотреть файл

@ -2,12 +2,18 @@ var FirebaseSync = function(Backbone, _, firebaseStoreName) {
var firebaseUserRef = 'https://gombot.firebaseIO.com/'+firebaseStoreName; var firebaseUserRef = 'https://gombot.firebaseIO.com/'+firebaseStoreName;
function getFirebaseStoreForUser(model) { function maybeInitFirebaseStoreForUser(model, callback) {
if (model.firebase) return _.defer(callback);
var firebaseReady = function(firebase) {
model.firebase = firebase;
callback();
};
var storePath = [ firebaseUserRef, var storePath = [ firebaseUserRef,
btoa(model.get("email")), btoa(model.get("email")),
model.keys.authKey, model.keys.authKey,
model.keys.authKey ].join('/'); model.keys.authKey ].join('/');
return new Backbone.Firebase(new Firebase(storePath)); new Backbone.Firebase(new Firebase(storePath), firebaseReady);
} }
function sync(method, model, options) { function sync(method, model, options) {
@ -15,8 +21,9 @@ var FirebaseSync = function(Backbone, _, firebaseStoreName) {
console.log("Error missing keys in model for firebase", model); console.log("Error missing keys in model for firebase", model);
return; return;
} }
model.firebase = model.firebase || getFirebaseStoreForUser(model); maybeInitFirebaseStoreForUser(model, function () {
Backbone.Firebase.sync(method, model, options); Backbone.Firebase.sync(method, model, options);
})
} }
return { return {

Просмотреть файл

@ -7,13 +7,20 @@ return (function() {
const USER_DATA_KEY = "userData"; const USER_DATA_KEY = "userData";
Backbone.Firebase = function(ref) { Backbone.Firebase = function(ref, callback) {
this._fbref = ref; this._fbref = ref;
this._children = []; this._children = [];
if (typeof ref == "string") { if (typeof ref == "string") {
this._fbref = new Firebase(ref); this._fbref = new Firebase(ref);
} }
var ready = function (snapshot) {
this._fbref.off("value", ready);
callback(this);
}.bind(this);
this._fbref.on("value", ready);
_.bindAll(this); _.bindAll(this);
this._fbref.on("child_added", this._childAdded); this._fbref.on("child_added", this._childAdded);
this._fbref.on("child_moved", this._childMoved); this._fbref.on("child_moved", this._childMoved);