Examples > Organizing Data > Index Example
Example from https://firebase.com/docs/platforms/web/guide/organizing-data.html
by Firebase
HTML
<script src="https://cdn.firebase.com/js/client/2.2.9/firebase.js"></script>
<script src="https://firebase.github.io/demo-utils-script/demo-utils.js"></script>
<div>
<h2>Mary's Groups</h2>
<ul class="groups"></ul>
</div>
<div>
<h2>Modify index</h2>
<ul class="index">
<li data-id="alpha">alpha <button></button></li>
<li data-id="bravo">bravo <button></button></li>
<li data-id="charlie">charlie <button></button></li>
<li data-id="delta">delta <button></button></li>
<li data-id="echo">echo <button></button></li>
</ul>
</div>
<div>
<h2>/users/mchen/groups</h2>
<pre></pre>
</div>
<p data-target="demo-links"></p>
CSS
pre {
background-color: #eee;
border: 1px solid #aaa;
padding: 10px;
border-radius: 10px;
width: auto;
display: block;
}
div {
width: 32%;
margin-right: 1%;
float: left;
}
JavaScript
function runExample(demoUrl) {
var fbRef = new Firebase(demoUrl);
var groupsRef = fbRef.child('groups');
var indexRef = fbRef.child('users/mchen/groups');
/******************
Monitor the index
for add/remove events
******************/
indexRef.on('child_added', added);
indexRef.on('child_removed', removed);
function added(idxSnap, prevId) {
// when an item is added to the index, fetch the data
groupsRef.child(idxSnap.key()).once('value', function (dataSnap) {
addToList(dataSnap.key(), dataSnap.val(), prevId);
});
}
function removed(snap) {
dropFromList(snap.key());
}
/**********************
Add and remove items from
the index when group buttons
are pressed
**********************/
// catch button clicks and trigger add/remove
watchForButtonClicks(addToIndex, dropFromIndex);
function addToIndex(id) {
indexRef.child(id).set(true);
}
function dropFromIndex(id) {
indexRef.child(id).remove();
}
/**************************
Demo fluff to build the UI
and make it semi-pretty
**************************/
var indexGroups = {};
indexRef.on('value', update);
function watchForButtonClicks(add, remove) {
$('ul.index button').click(function() {
var myId = $(this).closest('li').attr('data-id');
if( !indexGroups.hasOwnProperty(myId) ) {
add(myId);
}
else {
remove(myId);
}
});
}
function addToList(key, data, prevId) {
$prev = getPrevItem(prevId);
var $item = $('<li></li>')
.text(data.name)
.attr('data-id',key);
if( $prev ) {
$item.insertAfter($prev);
}
else {
$item.prependTo('ul.groups');
}
return $item;
}
function...