Skip to content

Instantly share code, notes, and snippets.

@neight-allen
Created May 12, 2017 16:41
Show Gist options
  • Save neight-allen/6b7f05c01023682d41ad5625febf2655 to your computer and use it in GitHub Desktop.
Save neight-allen/6b7f05c01023682d41ad5625febf2655 to your computer and use it in GitHub Desktop.
Sample code for students to break down into different reponsibilities
function Food(name, calories) {
this.name = name;
this.calories = calories;
}
$("document").ready(function() {
time = moment();
setIndexFoods();
})
function setIndexFoods() {
$.get("https://quantify-yourself.herokuapp.com/api/foods")
.done( function(foods) {
foods.forEach(function(foodItem) {
var row = "<tr class='food-row'>" +
"<td><input type='checkbox'/></td>" +
"<td class='food-name'>" +
name +
"</span></td> <td class='food-calories'>" +
calories
$('#diary-food-list').prepend(row);
$('#name-field input, #calories-field input').val('');
})
})
}
$('#food-filter input').keyup(function() {
var rows = $('#diary-food-list tr.food-row');
var filter = $('#food-filter input').val().toLowerCase();
rows.hide();
rows.each(function() {
var name = $(this).children('.food-name').text().toLowerCase();
if (name.indexOf(filter) >= 0) {
$(this).show();
}
});
})
function storeFood(name, calories) {
newFood = new Food(name, calories)
$.post("https://quantify-yourself.herokuapp.com/api/foods", newFood, function(data){
}).done( function(data) {
$('tr.food-row#undefined')
.data('id', data.rows[0].id)
})
}
function prependRow(name, calories, id) {
var row = "<tr class='food-row' data-id=" + id + ">" +
"<td class='food-name'><span contenteditable='true'>" +
name +
"</span></td> <td class='food-calories'><span contenteditable='true'>" +
calories +
"</span></td> <td class='food-delete'><button>-</button></td>";
$('#food-list').prepend(row);
$('#name-field input, #calories-field input').val('');
}
function raiseErrors(name, calories) {
if (name.length == 0) {
$('#name-field .validation-error').html('Please Enter a Name');
}
if (calories.length == 0) {
$('#calories-field .validation-error').html('Please Enter Calories');
}
}
$('#add-food').on('click', function() {
$('.validation-error').empty()
var name = $('#name-field input').val();
var calories = $('#calories-field input').val();
var table = $('#food-list')
if (name.length > 0 && calories.length > 0) {
prependRow(name, calories);
storeFood(name, calories);
} else {
raiseErrors(name, calories)
}
})
function removeFood(id) {
$.ajax({
url: "https://quantify-yourself.herokuapp.com/api/foods/"+ id,
type: 'DELETE'
})
}
$('table#food-list').on('click', '.food-delete', function() {
var id = $(this).parents('tr').data('id');
$(this).parents('tr').remove();
removeFood(id);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment