如何在准备好的文档中从Firebase获取数据

时间:2018-08-16 14:48:50

标签: javascript firebase firebase-realtime-database

我已经开发了这些Firebase脚本,希望在文档准备好后从Firebase数据中获得一些帮助。

第二个问题,如何使按钮(喜欢/不喜欢)单击一次(想要用户仅触发一次)?

HTML

// store the main Firebase URL
var firebaseURL = 'https://app-api-163321.firebaseio.com/like-button/';

// update the likeCounts shown in a <span> beside each blogpost
var postDivs = document.querySelectorAll('.post');

for (var i = 0; i < postDivs.length; i++) {
    var postID = postDivs[i].id;
    var numLikes = getLikeCount(postID);
}

// this function grabs the likeCount for a particular post from the Firebase
function getLikeCount(postID) {
    var thisPostRef = new Firebase(firebaseURL + postID + '/like-count/');
    thisPostRef.once('value', function (snapshot) {
        if (snapshot.val()) {
            document.querySelector('#' + postID + ' .like-count').innerHTML = snapshot.val() + ' likes';
        } else {
            return 0;
        }
    });
}

function likePost(id) {
    var postRef = new Firebase(firebaseURL + id);
    // get current number of likes here, so we can increment if any exist
    postRef.child('like-count').once('value', function (snapshot) {
        var currentLikes = snapshot.val() ? snapshot.val() : 0;
        postRef.update({
            'postID': id,
            'like-count': currentLikes + 1

        }, function (error) {
                console.log(error);
        });
        getLikeCount(id);
    });
}

function dlikePost(id) {
    console.log('running likePost() for post ID:', id);
    var postRef = new Firebase(firebaseURL + id);

    // get current number of likes here, so we can increment if any exist
    postRef.child('like-count').once('value', function (snapshot) {
        console.log('snapshot.val():', snapshot.val());
        var currentLikes = snapshot.val() ? snapshot.val() : 0;
        console.log('currentLikes:', currentLikes);
        postRef.update({
            'postID': id,
            'like-count': currentLikes - 1

        }, function (error) {
            if (error) {
                console.log('Data could not be saved:' + error);
            } else {
                console.log('Data saved successfully');
            }
        });

        getLikeCount(id);
    });
}
<script src='https://cdn.firebase.com/js/client/2.2.7/firebase.js'></script>


<div class="gpc" id="p72561979729402801623">
    <a class="btn btn-success  like bl1" data-id="13796" href="#" onclick="likePost('p72561979729402801623');">like</a>
    <div class="like-count bl2" />
    <a class="btn btn-danger  dislike bl3" href="#" onclick="dlikePost('p72561979729402801623');">dilike</a>
</div>

反正还有吗?

https://jsfiddle.net/vj8regwy/

1 个答案:

答案 0 :(得分:0)

编辑(添加了用于禁用客户端按钮的代码): 您应该了解并可以自己完成它

remove