mercredi 29 novembre 2017

how to get a single variable from orderbychild query

I'm reading some data from firebase, and I'm trying to get an event nearest to user's date.

However, what I currently have is reading through all data, by orderbychild() method which triggers bunch of functions because of displayEvent() being run each time.

How can i effectively reduce this by getting var=i into single result first, then run displayEvent(). This seems to be scope problem, and needs revision.

function searchStartDate(array,i){

            var userDate = new Date(); // for now
            var userMonth= userDate.getMonth(); // => 9
            var userHour= userDate.getHours(); // => 9
            var userMinute=userDate.getMinutes(); // =>  30


            var dbRef = firebase.database().ref("/data/")


               // Sorted According to Start Date
                 dbRef.orderByChild("calEvent,startDate").on("child_added", function(snapshot) {



                  var searchDate = new Date(snapshot.val().calEvent.startDate);

                   var searchMonth =   searchDate.getMonth(); // => 9
                    var  searchHour= searchDate.getHours(); // =>  30
                    var searchMinute=  searchDate.getMinutes(); // => 51

                    var nearestDate, nearestDiff = Infinity;
                    var diff = +searchDate - userDate;



                     if(searchDate > userDate && diff > 0 &&  diff < nearestDiff){
                              nearestDiff = diff;
                              nearestDate = Date(); 
                           var i =  snapshot.key;

                             displayEvent(i);

                              var resultDate = Date(nearestDate);
                       };




                /*  console.log('The key is: ' + snapshot.key + ' The Value is: ' + snapshot.val().calEvent.startDate);*/
                    document.getElementById("eventtime").innerHTML = resultDate;


                 });


     }

Aucun commentaire:

Enregistrer un commentaire