onsa
2/26/2017 - 6:24 PM

Firebase Database simple use cases - DOM crawler and local listeners not shown here

Firebase Database simple use cases - DOM crawler and local listeners not shown here

<!DOCTYPE html>
<html>
  <head>
		<script src="https://www.gstatic.com/firebasejs/.../firebase.js"></script>
		<script src="https://www.gstatic.com/firebasejs/.../firebase-app.js"></script>
		<script src="https://www.gstatic.com/firebasejs/.../firebase-database.js"></script>
		<script>
		  var config = {
		    apiKey: "...",
		    authDomain: "sympapp-....firebaseapp.com",
		    databaseURL: "https://sympapp-....firebaseio.com",
		    storageBucket: "sympapp-....appspot.com",
		    messagingSenderId: "..."
		  };
		  firebase.initializeApp(config);
		  var DB = firebase.database();
		  //  keep track of last key
      var lastKey = 0;
      var todo = {
      	title: '',
      	description: ''
      };
    	DB.ref('/todos/').on('value', function(responseList) {
  			if (responseList.val()) {
  				responseList.forEach(function(todo) {
  					todos[todo.key] = todo.val();
  					lastKey = parseInt(todo.key) + 1;
  				});
  			}
    	});
		</script>
	</head>
  <body>
    <div>
    	<div>
    		<div>
    			<h1>Add new ToDo</h1>
    			<form>
    				<input placeholder="title" type="text" />
    				<textarea placeholder="description"></textarea>
    				<button>Go</button>
    			</form>
    		</div>
    
    		<div>
    			<h1>Edit ToDo</h1>
    			<form>
    				<input placeholder="title" type="text" />
    				<textarea>description</textarea>
    				<button>Go</button>
    			</form>
    		</div>
    	</div>
    
    	<div>
    		<ul ID="todos">
    		  <!-- add todo title to label's innerHTML & duplicate as many times as todos.length OR use ng-repeat -->
    			<li><button>&times;</button><label></label></li>
    		</ul>
    	</div>
    </div>
	</body>
</html>
var update = function() {
	DB.ref('/todos/' + editKey).update(edit);
	edit = null;
	editKey = null;
};
var lookUp = function(refTodoId) {
	DB.ref('/todos/').once('value').then(function(todos) {
		for (var todoId in todos.val()) {
			if (parseInt(todoId) === parseInt(refTodoId)) {
        //  do something
				break;
			}
		}
	});
};
var del = function(todoId) {
	DB.ref('/todos/' + todoId).remove();
	if (todoId === editKey) {
		edit = null;
		editKey = null;
	}
};
var submit = function() {
	if (todo.title.length > 0 && todo.description.length > 0) {
		DB.ref('todos/' + lastKey).set({
			title: todo.title,
			description: todo.description
		}).then(function() {
			todo.title = '';
			todo.description = '';
		});
	}
};