Firebase incremental ID example

Enforces an incremental ID which matches a counter on data

by Firebase

HTML

<script src="https://cdn.firebase.com/js/client/2.2.9/firebase.js"></script>
<a target="_blank" href="https://gist.github.com/katowulf/6158392">Click here to see the security rules</a>

<h3>Current Id</h3>
<div></div>
<button id="inc">increment</button>
<button id="clear">reset data</button>

<h4>Try to make record without incrementing ID (should always fail)</h4>
<input type="text" id="custom" /><button id="customButton">add</button>

<pre id="data"></pre>

CSS

div {
    padding: 20px;
    font-size: 48px;
    border-radius: 15px;
    background-color: #fafafa;
    border: 1px solid #999;
    width: 75px;
}

h3 {
    clear: both;
    padding-top: 20px;
}

button {
   clear: both; 
}

pre {
    display: block;
}

p {
    color: red;
}

JavaScript

var fb = new Firebase("https://katowulf-examples.firebaseio.com/incid/");

// monitors changes and updates UI
fb.child('counter').on('value', updateDiv);
fb.on('value', updatePre);

// creates a new, incremental record
$('#inc').on('click', incId);

// resets the data
$('#clear').on('click', function() {
   fb.remove(); 
});

// attempts to create any id you put in
$('#customButton').on('click', function() {
   addRecord($('#custom').val()); 
});

var errId = 0;
// creates a new, incremental record
function incId() {
    // increment the counter
    fb.child('counter').transaction(function(currentValue) {
        return (currentValue||0) + 1
    }, function(err, committed, ss) {
        if( err ) {
           setError(err);
        }
        else if( committed ) {
           // if counter update succeeds, then create record
           // probably want a recourse for failures too
           addRecord(ss.val()); 
        }
    });
}

// creates new incremental record
function addRecord(id) {
    setTimeout(function() {
       fb.child('records').child('rec'+id).set('record #'+id, function(err) {
          err && setError(err);
       });        
    });
}

// for demo purposes
function updateDiv(ss) {
   $('div').text(ss.val()||0);
   $('#custom').val('rec'+(parseInt(ss.val(), 10)+1)); 
}

// for demo purposes
function updatePre(ss) {
   $('#data').text(JSON.stringify(ss.val(), null, 2));  
}

// for demo purposes
function setError(msg) {
    var id = ++errId;
    $('body').append('<p id="err'+id+'">'+msg+'</p>');
    setTimeout(function() { $('#err'+id).fadeOut(); }, 2500);
}