在Firebase中创建新目录并插入数据
我想动态地在Firebase中创建五个新目录。 我还想动态地在这些目录中插入数据。 我为此目的编写了这个jquery脚本。
for(var i=0; i<5; i++) { var dataRef = new Firebase('https://blr-reaction-buttons.firebaseio.com/' + i); dataRef.on('value', function (snapshot) { var tempdata = snapshot.val(); if (!tempdata) { tempdata=50; dataRef.set(tempdata); } }); }
但它不是创建多个目录,而是创建一个目录(实际上是最后一个目录)(下图)…
我只是不明白为什么会这样。 请帮忙。 任何forms的帮助将不胜感激。 提前致谢。
Firebase实际上没有目录,而是所有内容都是JavaScript对象。 这意味着与目录最接近的是包含另一个对象的键:)
换句话说,我假设您希望在Forge中看到类似的内容:
要使Firebase看起来像这样,您可以在本地创建JavaScript对象并使用set
将其保存到根节点。 然后,您可以使用读取回调value
来侦听更改。 这是实现此目的的代码:
这是一个反对你的直觉的异步性的经典案例。
当你调用dataRef.on('value',
它可能会到达服务器以获得你的那个值。这个操作可能需要很长时间,所以不要等待结果(这会阻止浏览器)而不是选择当值可用时,系统会给您回电。
不幸的是,在调用回调函数时,您已将dataRef
值更改为指向其他内容:最后一个dataRef 4
。
这就像您的代码按此顺序执行:
var i = 0 var dataRef = new Firebase('https://blr-reaction-buttons.firebaseio.com/' + i); dataRef.on('value', ... }; // Your callback is not invoked immediately, but only once the server returns the value. // But in the meantime your main code continues with the next iteration through the loop i = 1; var dataRef = new Firebase('https://blr-reaction-buttons.firebaseio.com/' + i); dataRef.on('value', ... }; // Same as before: we're now waiting for 2 values to become available i = 2; var dataRef = new Firebase('https://blr-reaction-buttons.firebaseio.com/' + i); dataRef.on('value', ... }; // Let's say that all values becomes available at this point, so your callback code executes function (snapshot) { var tempdata = snapshot.val(); if (!tempdata) { tempdata=50; dataRef.set(tempdata); } }); function (snapshot) { var tempdata = snapshot.val(); if (!tempdata) { tempdata=50; dataRef.set(tempdata); } }); function (snapshot) { var tempdata = snapshot.val(); if (!tempdata) { tempdata=50; dataRef.set(tempdata); } });
注意这三种情况下的行dataRef.set
? 此时,单个变量dataRef
引用ref 2
处的对象。 您最终将值设置为相同的ref三次。
一个简单的解决方案是简单地始终设置值:
for(var i=0; i<5; i++) { var dataRef = new Firebase('https://blr-reaction-buttons.firebaseio.com/' + i); var tempdata=50; dataRef.set(tempdata); }
Jenny Murphy的方法也会很好。 因为将在所谓的闭包中捕获不同的dataRef
值(google for javascript closure或者立即调用函数表达式以了解更多信息)。