Skip to content

Instantly share code, notes, and snippets.

@sumskyi
Last active December 11, 2015 04:48
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 sumskyi/4547226 to your computer and use it in GitHub Desktop.
Save sumskyi/4547226 to your computer and use it in GitHub Desktop.
knockout.js + CoffeeScript learn.knockoutjs.com: Working with Lists and Collections
%h2
Your seat reservations
%span{:"data-bind" => "text: seats().length"}
%table
%thead
%tr
%th Passenger name
%th Meal
%th Surcharge
%th
%tbody{:"data-bind" => "foreach: seats"}
%tr
%td
%input{:"data-bind" => "value: name"}
%td
%select{:"data-bind" => "options: $root.availableMeals, value: meal, optionsText: 'mealName'"}
%td{:"data-bind" => "text: formattedPrice"}
%td
%a{:href => '#', :"data-bind" => "click: $root.removeSeat"}Remove
%button{:"data-bind" => "click: addSeat, enable: seats().length < 5"} Reserve another seat
%h3{:"data-bind" => "visible: totalSurcharge() > 0"}
Total surcharge: $
%span{:"data-bind" => "text: totalSurcharge().toFixed(2)"}
$ ->
class SeatReservation
constructor: (@name, initialMeal) ->
self = @
@meal = ko.observable(initialMeal)
@formattedPrice = ko.computed ->
price = self.meal().price
if price
"$#{price.toFixed(2)}"
else
"None"
class ReservationsViewModel
constructor: ->
# Non-editable catalog data - would come from the server
@availableMeals = [
{ mealName: "Standard (sandwich)", price: 0 },
{ mealName: "Premium (lobster)", price: 34.95 },
{ mealName: "Ultimate (whole zebra)", price: 290 }
]
# Editable data
@seats = ko.observableArray([
new SeatReservation("Steve", @availableMeals[0]),
new SeatReservation("Bert", @availableMeals[1])
])
@totalSurcharge = ko.computed(
->
total = 0
total += el.meal().price for idx, el of @seats()
total
@
)
addSeat: ->
@seats.push new SeatReservation("", @availableMeals[2])
return
removeSeat: (seat) =>
@seats.remove seat
return
ko.applyBindings(new ReservationsViewModel());
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment