Skip to content

Instantly share code, notes, and snippets.

@kasima
Created May 18, 2011 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kasima/979259 to your computer and use it in GitHub Desktop.
Save kasima/979259 to your computer and use it in GitHub Desktop.
Making your js testable
// From http://front-end-testing-talk.elabs.se/
// Seen at RailsConf 2011
// Typical jQuery
$('#whiskies li').each(function() {
var li = $(this);
var price = li.attr('data-price');
var addLink = $('<a class="add-to-cart" href="#">Add to cart</a>');
addLink.appendTo(li);
addLink.click(function() {
var item = $('<li>' + li.attr('data-name') + '</li>');
item.appendTo('#cart .list');
item.append('<span class="price">' + price + '</span>');
var currentAmount = parseInt($('#cart .total .amount').text());
var newAmount = currentAmount + parseInt(price);
$('#cart .total .amount').text(newAmount);
return false;
});
});
// Refactored for more testability
var Cart = function(element) {
this.element = $(element);
this.list = this.element.find('.list');
this.total = this.element.find('.total .amount');
this.items = [];
};
Cart.prototype.addItem = function(item) {
element = $('<li>' + item.name + '<span class="price">' +
item.price + '</span></li>').appendTo(this.list);
this.items.push({ name: item.name, price: item.price, });
this.updateTotal();
};
Cart.prototype.updateTotal = function() {
sum = 0;
$(this.items).each(function() { sum += this.price });
this.total.text(sum);
};
// In coffeescript
class Cart
constructor: (element) ->
@element = $(element)
@list = @element.find('.list')
@total = @element.find('.total .amount')
@items = []
addItem: (item) ->
element = $("<li>#{item.name}<span class='price'>" +
"#{item.price}</span></li>")
element.appendTo(@list)
@items.push(name: item.name, price: item.price)
@updateTotal()
updateTotal: ->
sum = 0
sum += item.price for item in @items
@total.text(sum)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment