Firebase children/transaction

by Frank van Puffelen

HTML

<script src="http://static.firebase.com/v0/firebase.js"></script>
Example for <a href='http://stackoverflow.com/q/24714529/209103'>Notification of final commit in batch transactions</a><br/>
<button id='init'>Create (or re-create) items</button>
<div id='log'></div>
<button id='action'>Check-in/check-out some items</button>

JavaScript

var ref = new Firebase("https://stackoverflow.firebaseio.com/24714529/");
var items = ref.child("items");

var username = prompt("What\'s your name? We'll use it to check out some items in your name.");

var ITEM_COUNT = 10;

var log = document.getElementById('log');

document.getElementById('init').addEventListener('click', function(event) {
    for (var i=0; i < ITEM_COUNT; i++) {
        items.child(i).set({ 
            name: 'item_' + i, 
        });
    }
});

function getItemAsString(item) {
    return item.name + ': ' + (item.checked_out_by ? ' checked_out_by='+item.checked_out_by : '');
}

items.on('child_added', function(snapshot) {
    var val = snapshot.val();
    var pre = document.createElement('pre');
    pre.id = snapshot.val().name;
    pre.innerText = getItemAsString(val);
    log.appendChild(pre);
});

items.on('child_changed', function(snapshot) {
    var val = snapshot.val();
    var pre = document.getElementById(val.name);
    console.log('value toggle: '+val.name);
    pre.innerText = getItemAsString(val);
});

function toggleRandomItem() {
    var i = Math.floor(ITEM_COUNT * Math.random());
    items.child(i).transaction(function(current_value) {
        if (!current_value.checked_out_by) {
            // not checked out -> check it out
            current_value.checked_out_by = username;
        }
        else if (current_value.checked_out_by == username) {
            // checked out by me -> check it in
            delete current_value.checked_out_by;
        }
        else {
            // checked out by someone else -> abort transaction
            return;
        }
        return current_value;
    }, function(error, committed, snapshot) {
        if (error) {
            console.log('error callback: '+error);
            throw error;
        } else if (!committed) {
            console.log('not committed callback');
            console.log(snapshot.val()); // this is unmodified, so no need to update
        } else {
           ...