javascript - Pick random value from firebase snapshot -
i'm using firebase's foreach each child in tree url
objective, when page loads grab random item firebase , show it
data structure
grabbit (table name) active (for active items sale) category (the category of item ie womensclothes, mensshoes etc) unique id of item
on page load go http://gamerholic.firebase.com/grabbit/active , grab 1 of categories , return it..
script
var grabbitref = new firebase('https://gamerholic.firebaseio.com/grabbit/active/'); grabbitref.on('value', function(snapshot) { if(snapshot.val() === null) { alert("invalid"); } else { // snap shot data: snapshot.foreach(function(snapshot) { var name = snapshot.name(); alert(name); }); } });
after have random category "electronics", new snapshot , have return random item that's in electronics
var grabbitref = new firebase('https://gamerholic.firebaseio.com/grabbit/active/'+name); grabbitref.on('value', function(snapshot) { if(snapshot.val() === null) { alert("invalid"); } else { // snap shot data: snapshot.foreach(function(snapshot) { var id = snapshot.name(); alert(id); }); } });
with id can details of item
var grabbitref = new firebase('https://gamerholic.firebaseio.com/grabbit/active/'+name+'/'+id);
it's not possible grab random item list in firebase, unfortunately. can limit(1) grab first item, or endat().limit(1) grab last item.
if you're using foreach, can grab items , picking 1 @ random, using math.random. example:
var = 0; var rand = math.floor(math.random() * snapshot.numchildren()); snapshot.foreach(function(snapshot) { if (i == rand) { // picked random item, snapshot.val(). } i++; });
Comments
Post a Comment