This is more of a JavaScript Closure question than a Firebase question. In the following code, the Firebase callback isn't recognizing the variable myArr in the parent scope.
function show_fb() {
var myArr = [];
var firebase = new Firebase('https://scorching-fire-6816.firebaseio.com/');
firebase.on('child_added', function(snapshot) {
var newPost = snapshot.val();
myArr.push(newPost.user);
console.log(myArr); // works
});
console.log(myArr); // doesn't work. myArr in the firebase.on callback is
// not altering myArr
return myArr;
};
The callback is recognizing/modifying
myArr
perfectly fine. The problem is that when your "doesn't work"-labeledconsole.log(myArr)
executes, the callback hasn't fired yet.Let's change your code a bit:
Now it might be a bit easier to see what's going on.
child_added
that will callon_post_added
for every post that is added to your FirebaseHandling asynchronous code/callbacks like this takes some getting used to, but is crucial to working with Firebase or any other AJAX-like or event driven technology. Putting the callback's code into a separate function sometimes makes it a bit easier to see what's going on.
In the case of Firebase it may also help to realize that the event is called
child_added
for a reason. It is called whenever a child is added to the Firebase, not just when you first register your callback. So minutes later when some other client adds a child, your callback will still fire, adding a new child tomyArr
. At that stage the code in steps 4 and 5 above will long have executed and will not execute again.The solution is simple: put anything that you want to do after a child is added into your callback:
The child_added event is not immediately executed, therefore is not synchronous and you can't rely on it to have executed, before the log call at the end of your function.
The procedure is:
If Firebase makes ajax call(it probably does), then callback function(snapshot){..} is called after return statement. So function show_fb always returns [].
for instance: