Knockout - and OData - person viewmodel sample

by johnpapa

HTML

<script src="http://knockoutjs.com/js/knockout-2.0.0.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<h4>people array (observable properties, observable array)</h4>
<ul data-bind="foreach: people">
    <li>
        <input data-bind="value:firstName, valueUpdate:'afterkeydown'"/>
        <input data-bind="value:lastName, valueUpdate:'afterkeydown'"/>
    </li>
</ul>
<br/>
<button data-bind="click:add" class="btn">Add New Person</button>
<br/><br/>
<h4>people array, as changes are made</h4>
<pre data-bind="text:displayPeopleJS">
</pre>

JavaScript

var my = {};

my.Person = function() {
    var self = this;
    self.firstName = ko.observable();
    self.lastName = ko.observable();
};

my.vm = (function() {
    var people = ko.observableArray();
    
    var mapPeople = function(results) {
        var rawPeopleArray = results;
        for (var i = 0; i < rawPeopleArray.length; i++) {
            var p = rawPeopleArray[i];
            people.push(
            new my.Person().firstName(p.FirstName).lastName(p.LastName));
        };
    };

    var testMe = function() {
        var pocoPeople = ko.toJS(people);
        console.log(pocoPeople[0].firstName);
    };

    var save = function() {
        var pocoPerson = ko.toJS(person);
        OData.request({
            requestUri: person.__metadata.uri,
            method: "PUT",
            data: pocoPerson
        }, success = function(data, response) {
            alert("Saved");
        }, saveError = function(error) {
            alert("Error occurred " + error.message);
        });
    };

    var add = function() {
        people.push(
            new my.Person()
            .firstName('new')
            .lastName('person'));
    };

    var displayPeopleJS = ko.computed(function() {
        return JSON.stringify(ko.toJS(people), null, 2);
    });

    return {
        people: people,
        mapPeople: mapPeople,
        testMe: testMe,
        save: save,
        add: add,
        displayPeopleJS: displayPeopleJS
    };
})();

// Only call this once per page. 
// You dont want to call it every time you reload. 
// The bindings are already set.
ko.applyBindings(my.vm);

// Now pretend we get an array of people.
var somePeopleFromSomeWebService = [{
    'FirstName': 'John',
    'LastName': 'Papa'},
{
    'FirstName': 'Julie',
    'LastName': 'Lerman'}];

// map the object from the web service to your vm.person instance
my.vm.mapPeople(somePeopleFromSomeWebService);

my.vm.testMe();