[英]Passing variable in parent scope to callback function
这更像是一个JavaScript Closure问题而不是Firebase问题。 在以下代码中,Firebase回调未识别父作用域中的变量myArr。
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;
};
回调是完全myArr
地识别/修改myArr
。 问题是当你的“不工作”标记的console.log(myArr)
执行时,回调还没有被触发。
让我们稍微改变你的代码:
var myArr = [];
function show_fb() {
var firebase = new Firebase('https://scorching-fire-6816.firebaseio.com/');
firebase.on('child_added', on_post_added); // steps 1-3
console.log(myArr); // step 4
return myArr; // step 5
};
function on_post_added(snapshot) { // step 6
var newPost = snapshot.val();
myArr.push(newPost.user); // step 7
console.log(myArr); // step 8
}
现在可能更容易看到发生了什么。
child_added
注册了一个监听child_added
,该监听器child_added
添加到您的Firebase的每个帖子调用on_post_added
像这样处理异步代码/回调需要一些人习惯,但对于使用Firebase或任何其他类似AJAX或事件驱动的技术至关重要。 将回调代码放入一个单独的函数有时可以更容易地看到正在发生的事情。
对于Firebase,它也可能有助于意识到事件被称为child_added
有一个原因。 只要孩子被添加到Firebase,就会调用它,而不仅仅是在您第一次注册回调时。 所以几分钟后,当其他一些客户端添加一个孩子时,你的回调仍然会触发,向myArr
添加一个新的孩子。 在那个阶段,上面的步骤4和5中的代码将长期执行,并且不会再次执行。
解决方案很简单:在将子项添加到回调中之后放置您想要执行的任何操作:
var myArr = [];
function show_fb() {
var firebase = new Firebase('https://scorching-fire-6816.firebaseio.com/');
firebase.on('child_added', on_post_added);
};
function on_post_added(snapshot) {
var newPost = snapshot.val();
myArr.push(newPost.user);
console.log(myArr);
// do whatever else you need to do for a new post
}
child_added事件不会立即执行,因此不是同步的,并且在函数结束时的日志调用之前,您不能依赖它来执行。
程序是:
如果Firebase进行ajax调用(可能确实如此),则在return语句之后调用回调函数(快照){..}。 所以函数show_fb总是返回[]。
例如:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.