1

I was wondering why this jQuery function is not returning any value from the function. It does increase the value in Firebase and everything else works fine except returning value. Badly stuck with this for hours :(

 $(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;
}

and the HTML part is something like that..

<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>

Any kind of help would be appreciated.

1 Answers1

4

The firebase api is an asynchronous api, so you can't return value frrm that instead you can use a callback to do the processing

$(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)
    });
}
Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531