Created
May 21, 2013 01:29
-
-
Save SamSamskies/5616956 to your computer and use it in GitHub Desktop.
Behavior Drill: Grocery List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function List(listType) { | |
this.items = []; | |
this.total = 0; | |
this.listType = listType; | |
this.init = function() { | |
if (this.listType === 'store') { | |
this.makeItemsDraggable(); | |
this.populateItems(); | |
} else { | |
this.makeListDroppable(); | |
} | |
}; | |
this.addItem = function(item) { | |
this.items.push(item); | |
this.total += item.price; | |
}; | |
} | |
function Item(name, price) { | |
this.name = name; | |
this.price = price; | |
} | |
var store = new List("store"); | |
var grocery = new List("grocery"); | |
store.populateItems = function() { | |
$('.item').each(function() { | |
var name = $(this).find(">:first-child").text(); | |
var price = parseFloat($(this).find(">:last-child").text()); | |
store.addItem(new Item(name, price)); | |
}); | |
}; | |
store.makeItemsDraggable = function() { | |
$(".item").draggable({ helper: "clone" }); | |
}; | |
grocery.makeListDroppable = function() { | |
$("#grocery_list").droppable({ | |
drop: function(event, ui) { | |
var itemName = $(ui.draggable.clone()).find('.item_name').text(); | |
var itemPrice = parseFloat($(ui.draggable.clone()).find('.item_price').text()); | |
grocery.addItem(new Item(itemName, itemPrice)); | |
grocery.render(); | |
} | |
}); | |
}; | |
grocery.render = function() { | |
$('#grocery_list').find('tbody').empty(); | |
$.each(this.items, function(){ | |
var htmlString = ['<tr><td>', this.name, '</td><td>', this.price, '</td></tr>'].join(''); | |
$('#grocery_list').find('tbody').append(htmlString); | |
}); | |
$('#total_cost').text(this.total.toFixed(2)); | |
}; | |
$(document).ready(function() { | |
store.init(); | |
grocery.init(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment