Knockout foreach binding

Bingind a table to an array list

by Dejan Vasic

HTML

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<h4>People</h4>

<ul data-bind="foreach: Allergies">
    <li>Name at position <span data-bind="text: $index"> </span>: <span data-bind="text: foo"> </span>

        <input type="checkbox" data-bind="checked: selected" />
    </li>
</ul>
<input id="scream" type="button" value="view updated model" />
<input id="additem" type="button" value="Add Item" />
<div id="output"></div>

JavaScript

Model = function () {
    this.Name = 'Borat';
    this.Allergies = ko.observableArray([{
        foo: 'something else now',
        selected: true
    }]);
};

var testModel = new Model();
ko.applyBindings(testModel);

$().ready(function () {
    $('#scream').on('click', function () {
        $('#output').html(JSON.stringify(testModel.Allergies()));
    });
    $('#additem').on('click', function () {
        var newItem = {
            foo: 'new item',
            selected: false
        };
        testModel.Allergies.push(newItem);
    });
});