我试图制作一个简单的网页,只是为了玩Firebase。我目前正在处理用户上传照片并将其存储以及在数据库中对它们的引用。我有一个工作版本,除了唯一的问题是如果多个用户同时打开页面,只有最新的帖子会持续。我想使用实时功能来克服这个问题并提出这个问题。
var postRef = firebase.database().ref('variables/postNumber');
postRef.on('value',function(snapshot) {
var postName = snapshot.val();
var uploader = document.getElementById('uploader');
var filebutton = document.getElementById('filebutton');
// get file
filebutton.addEventListener('change', function(e) {
var file = e.target.files[0];
var ext = file.name.split('.').pop();;
console.log(postName);
console.log(ext);
//create a storage ref
var storageRef = firebase.storage().ref('posts/' + postName + "." + ext);
var task = storageRef.put(file);
publishPost(postName, ext);
function publishPost(postName, ext) {
firebase.database().ref('posts/' + postName).set({
postID: postName,
postDate: Date(),
fileType : ext
});
firebase.database().ref('variables/').set({
postNumber: postName + 1
});
}
task.on('state_changed',
function progress(snapshot){
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) *100;
uploader.value = percentage;
},
function error(err){
},
function complete(postName, ext){
uploader.value = 0;
window.alert('Your meme Uploaded correctly');
},
);
});
});
这很好用,总是更新postName变量,除非新用户发布,它会将每个帖子重写为新帖子。例如,如果用户A在用户B已经在页面上时发布图片,那么当用户B发布时,他的帖子将在第一次上载两次时覆盖用户A的帖子。任何人都可以解释为什么会这样吗?我正在考虑移动监听器来启动该功能,但不确定这是否是正确的选择。
答案 0 :(得分:1)
每次检测到新值时,事件侦听器都会附加到按钮上。这意味着change
上的filebutton
事件监听器根本不在观察者中。
工作代码:
let postName = null;
var postRef = firebase.database().ref('variables/postNumber');
postRef.on('value', function(snapshot) {
const value = snapshot.val();
if (value === null) {
// Handle error when no value was returned
return;
}
postName = value;
});
var uploader = document.getElementById('uploader');
var filebutton = document.getElementById('filebutton');
filebutton.addEventListener('change', function(e) {
if (postName === null) {
// Handle the case then post name is still null (either wan't loaded yet or couldn't be loaded)
return;
}
var file = e.target.files[0];
var ext = file.name.split('.').pop();;
//create a storage ref
var storageRef = firebase.storage().ref('posts/' + postName + "." + ext);
var task = storageRef.put(file);
publishPost(postName, ext);
function publishPost(postName, ext) {
firebase.database().ref('posts/' + postName).set({
postID: postName,
postDate: Date(),
fileType : ext
});
firebase.database().ref('variables/').set({
postNumber: postName + 1
});
}
task.on('state_changed',
function progress(snapshot){
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) *100;
uploader.value = percentage;
},
function error(err){
},
function complete(postName, ext){
uploader.value = 0;
window.alert('Your meme Uploaded correctly');
});
});