javascript - In Firebase when using push() How do I pull the unique ID -
i'm attempting add/remove entries firebase database. want list them in table added/modified/removed (front end) need way uniquely identify each entry in order modify/remove. firebase adds unique identifier default when using push(), didn't see referencing how select unique identifier in api documentation. can done? should using set() instead i'm creating unique id?
i've put quick example using tutorial:
<div id='messagesdiv'></div> <input type='text' class="td-field" id='nameinput' placeholder='name'> <input type='text' class="td-field" id='messageinput' placeholder='message'> <input type='text' class="td-field" id='categoryinput' placeholder='category'> <input type='text' class="td-field" id='enabledinput' placeholder='enabled'> <input type='text' class="td-field" id='approvedinput' placeholder='approved'> <input type='button' class="td-field" id='submit' value="revove" onclick="msgref.remove()"> <script> var mydataref = new firebase('https://unique.firebase.com/'); $('.td-field').keypress(function (e) { if (e.keycode == 13) { var name = $('#nameinput').val(); var text = $('#messageinput').val(); var category = $('#categoryinput').val(); var enabled = $('#enabledinput').val(); var approved = $('#approvedinput').val(); mydataref.push({name: name, text: text, category: category, enabled: enabled, approved: approved }); $('#messageinput').val(''); } }); mydataref.on('child_added', function(snapshot) { var message = snapshot.val(); displaychatmessage(message.name, message.text, message.category, message.enabled, message.approved); }); function displaychatmessage(name, text, category, enabled, approved, ) { $('<div/>').text(text).prepend($('<em/>').text(name+' : '+category +' : '+enabled +' : '+approved+ ' : ' )).appendto($('#messagesdiv')); $('#messagesdiv')[0].scrolltop = $('#messagesdiv')[0].scrollheight; }; </script>
now lets assume have 3 rows of data:
fred : 1 : 1 : 1 : test message 1 fred : 1 : 1 : 1 : test message 2 fred : 1 : 1 : 1 : test message 3
how go uniquely identifying row 2?
in firebase database this:
-databasename -iuxesusiny6xiahcxa0 approved: "1" category: "1" enabled: "1" name: "fred" text: "test message 1" -iuxetjwwohv0lyep5hf approved: "1" category: "1" enabled: "1" name: "fred" text: "test message 2" -iuxeuwgbmth4xk9qadm approved: "1" category: "1" enabled: "1" name: "fred" text: "test message 3"
to "name" of snapshot (in case, id created push()) call name() this:
var name = snapshot.name();
if want name has been auto-generated push(), can call name() on returned reference, so:
var newref = mydataref.push(...); var newid = newref.name();
note: snapshot.name()
has been deprecated. see other answers.
Comments
Post a Comment