Skip to content

Instantly share code, notes, and snippets.

@Xom
Last active January 5, 2017 09:14
Show Gist options
  • Save Xom/7108193 to your computer and use it in GitHub Desktop.
Save Xom/7108193 to your computer and use it in GitHub Desktop.
Firebase checklist
<html>
<head>
<title>A checklist that syncs via Firebase</title>
<script type='text/javascript' src='https://cdn.firebase.com/v0/firebase.js'></script>
<script>
var fbref_checkboxen = new Firebase('https://checkboxen.firebaseio.com/');
fbref_checkboxen.on('child_added', function(snapshot) {
var sid = sanitize_id(snapshot.name());
var sstr_text = sanitize(snapshot.val().text, true);
var elem_newDiv = document.createElement('div');
elem_newDiv.setAttribute('id', 'div' + sid);
elem_newDiv.innerHTML = '<input type="checkbox" id="' + sid + '" onChange="updateItem(\'' + sid + '\')" '
+ (snapshot.val().checked ? 'checked ' : '') + '/>'
+ '<label for="' + sid + '">' + sstr_text
+ '</label> <small><a href="javascript:removeItem(\'' + sid + '\')">[remove]</a></small>';
document.getElementById('uberDiv').appendChild(elem_newDiv);
});
fbref_checkboxen.on('child_changed', function(snapshot) {
document.getElementById(sanitize_id(snapshot.name())).checked = snapshot.val().checked;
});
fbref_checkboxen.on('child_removed', function(snapshot) {
document.getElementById('uberDiv').removeChild(document.getElementById('div' + sanitize_id(snapshot.name())));
});
function addItem() {
var elem_newText = document.getElementById('newText');
var ustr_text = elem_newText.value;
if (ustr_text !== '') {
fbref_checkboxen.push({checked: false, text: ustr_text}, function(error) {
if (error) {
document.getElementById('newText').value = 'Failed to add "' + ustr_text + '".';
}
});
elem_newText.value = '';
}
}
function updateItem(str_id) {
fbref_checkboxen.child(str_id).update({checked: document.getElementById(str_id).checked});
}
function removeItem(str_id) {
fbref_checkboxen.child(str_id).remove();
}
function sanitize(ustr, bool_useWhitelist) {
if (bool_useWhitelist) {
var WHITELIST = '\\/?p>|\\/?h1>|\\/?h2>|\\/?h3>|\\/?h4>|\\/?h5>|\\/?h6>|\\/?ol>|\\/?ul>|\\/?li>|\\/?blockquote>|\\/?center>|\\/?pre>|\\/?em>|\\/?strong>|\\/?code>|\\/?samp>|\\/?kbd>|\\/?var>|\\/?b>|\\/?i>|\\/?u>|\\/?small>|\\/?s>|\\/?big>|\\/?strike>|\\/?tt>|\\/?br>|\\/?bdo>|\\/?del>|\\/?ins>|\\/?sub>|\\/?sup>|\\/?wbr>';
var regex = '<(?!(' + WHITELIST + '))[^>]*>';
return ustr.replace(new RegExp(regex, 'gi'), '');
}
var regex = '<[^>]*>';
return ustr.replace(new RegExp(regex, 'gi'), '');
}
function sanitize_id(ustr_id) {
var regex = '[^-A-Za-z0-9+/=_]';
return ustr_id.replace(new RegExp(regex, 'gi'), '');
}
</script>
</head>
<body>
<button type="button" onclick="addItem()">add item</button>
<input id="newText" size="64" />
<div id="uberDiv" />
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment