Meal Upgrades w/AJAX

Example from Knockout documentation that has been modified to use ajax. The data is sent as a post to the echo service to simulate an ajax get (presumably from a database, etc.). A delay of 5 sec mimics a long asynchronous call.

by agoodno

HTML

<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-1.2.1.js"></script>
<h3>Meal upgrades</h3>
<p>Make your flight more bearable by selecting a meal to match your social and economic status.</p>
Chosen meal: <select data-bind="options: availableMeals, optionsText: 'mealName', value: chosenMeal"></select>
<p>
    You've chosen: 
    <b data-bind="text: chosenMeal().description"></b>
    (price: <span data-bind='text: formatPrice(chosenMeal().extraCost)'></span>)
</p>

JavaScript

function formatPrice(price) {
    return price === 0 ? "Free" : "$" + price.toFixed(2);
}

var availableMeals = ko.observableArray([{
    mealName: '---Select---',
    description: 'None',
    extraCost: 0}]);

var viewModel = {
    chosenMeal: ko.observable(availableMeals[0])
};

viewModel.addAvailableMeal = function(availableMeal) {
    availableMeals.push(availableMeal);
};

ko.applyBindings(viewModel);

$.ajax({
    data: {
        json: JSON.stringify([{
            mealName: 'Standard',
            description: 'Dry crusts of bread',
            extraCost: 0},
        {
            mealName: 'Premium',
            description: 'Fresh bread with cheese',
            extraCost: 9.95},
        {
            mealName: 'Deluxe',
            description: 'Caviar and vintage Dr Pepper',
            extraCost: 18.50}]),
        delay: 5
    },
    type: 'POST',
    url: '/echo/json/',
    success: function(meals) {
        for (var meal in meals) {
            if (meals.hasOwnProperty(meal)) {
                viewModel.addAvailableMeal(meals[meal]);
            }
        }
    }
});