在Firebase中创建新目录并插入数据 [英] Create New Directory and Inserting Data in Firebase
问题描述
我想动态地在Firebase中创建五个新目录。我还想动态地在这些目录中插入数据。我为此编写了这个jquery脚本。
i want to create five new directories in Firebase dynamically. Also i want to insert data in those directories dynamically. I wrote this jquery script for that purpose.
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);
}
});
}
但它不是创建多个目录,而是创建一个目录(实际上是最后一个)(下图)...
but instead of creating multiple directories, it just create one directory (in fact the last one) (pic below)...
我只是不明白为什么会这样。请帮忙。任何形式的帮助将不胜感激。在此先感谢。
I just don't understand why this is happening. Pls help. Any kind of help would be appreciated. Thanks in advance.
推荐答案
Firebase实际上没有目录,而是一切都是JavaScript对象。这意味着与目录最接近的是包含另一个对象的键:)
Firebase doesn't really have directories, but instead everything is a JavaScript object. This means that the closest thing to a directory is a key that contains another object :)
换句话说,我假设您希望在Forge中看到类似的内容:
In other words, I'm assuming you want to see something like this in Forge:
制作您的Firebase看起来像这样,您可以在本地创建一个JavaScript对象,并使用 set
将其保存到根节点。然后,您可以使用读回调值
来侦听更改。以下是实现此目的的代码:
To make your Firebase look like that, you can create a JavaScript object locally and save it to the root node using set
. You can then use the read callback value
to listen for changes. Here's the code that implements this:
<html>
<head>
<script src='https://cdn.firebase.com/js/client/1.0.15/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'>
</script>
</head>
<body>
<script>
/* Write 5 numbered objects, each set to 50 */
// Create a new Firebase data reference to the root
var dataRef =
new Firebase('https://test-firebase-please-ignore.firebaseio.com/');
// Create a JavaScript object to hold stuff
var tempData = {};
// Add 5 things to it
for(var i=0; i<5; i++) {
tempData[i] = {value: 50};
}
// Save it to Firebase
dataRef.set(tempData);
/* Meanwhile, create a listener that gets updates when the data changes */
dataRef.on('value', function(snapshot) {
// Log the whole thing
console.log(snapshot.val());
});
</script>
</body>
</html>
这篇关于在Firebase中创建新目录并插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!