从jQuery函数返回值

时间:2015-03-22 10:36:54

标签: jquery function firebase

我想知道为什么这个jQuery函数没有从函数返回任何值。它确实增加了Firebase中的值,除了返回值之外,其他一切正常。几个小时都严重困扰着这一点:(

 $(function(){
  $('.post').each(function(){
    var $this = $(this);
    var postTitle = $this.find('.title').text();

    //create separate firebase reference
    var postRef = new Firebase('https://bloganalyzer-view-stat.firebaseio.com/trying/'+postTitle);

    var pData = getFirebaseData(postRef,'post');
    $this.find('.count').empty().html(pData);
  });
});

function getFirebaseData(r,bp){
  var data;
  r.once('value', function(snap) {
    data = snap.val();
    if (data == null) {data=1;}
    else if(bp=='blog') {data+=10;}
    else if(bp=='post') {data+=1;}
    r.set(data);
  });
  return data;
}

并且HTML部分就是这样......

<div class="post">
  <span class="title">Title 1</span>
  <span class="viewCount"></span>
</div>
<div class="post">
  <span class="title">Title 2</span>
  <span class="viewCount"></span>
</div>

任何形式的帮助都将受到赞赏。

1 个答案:

答案 0 :(得分:4)

firebase api是一个异步api,所以你不能返回值frrm而是你可以使用回调来进行处理

$(function () {
    $('.post').each(function () {
        var $this = $(this);
        var postTitle = $this.find('.title').text();

        //create separate firebase reference
        var postRef = new Firebase('https://bloganalyzer-view-stat.firebaseio.com/trying/' + postTitle);

        //pass a callback to getFirebaseData which will be called once the request is completed
        getFirebaseData(postRef, 'post', function (pData) {
            //this will get called once the request is completed
            $this.find('.count').html(pData);
        });
    });
});
//accept the callback as the last param which is a function
function getFirebaseData(r, bp, callback) {
    r.once('value', function (snap) {
        var data = snap.val();
        if (data == null) {
            data = 1;
        } else if (bp == 'blog') {
            data += 10;
        } else if (bp == 'post') {
            data += 1;
        }
        r.set(data);
        //once the value of data is calculated call the callback and pass the value to it instead of trying to return it
        callback(data)
    });
}