Created
May 9, 2012 16:39
-
-
Save msarchet/2646431 to your computer and use it in GitHub Desktop.
Example 4 for the knockout talk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.js"></script> | |
<script src="https://raw.github.com/bestiejs/lodash/master/lodash.js"></script> | |
<table > | |
<tr> | |
<th>First Name</th> | |
<th>Last Name</th> | |
<th>Phones</th> | |
</tr> | |
<tbody data-bind="foreach: contacts"> | |
<tr><td><input data-bind="value: firstName" /></td> | |
<td><input data-bind="value: lastName" /></td> | |
<td> | |
<table> | |
<tbody data-bind"foreach: phoneNumbers"> | |
<tr> | |
<td><input data-bind="value: phoneNumber" /></td> | |
<td><input data-bind="value: phoneType" /></td> | |
</tr> | |
</tbody> | |
</table> | |
</td> | |
</tr> | |
</tbody> | |
</table> | |
<textarea data-bind="value: asJson"> | |
</textarea> | |
<script type="text/javascript"> | |
var phoneModel = function(number, type) { | |
var self = this; | |
self.phoneNumber = number; | |
self.phoneType = type; | |
}; | |
var contactModel = function(first, last, numbers) { | |
var self = this; | |
self.firstName = first; | |
self.lastName = last; | |
self.phoneNumbers = numbers; | |
}; | |
var viewModel = function(contacts) { | |
var self = this; | |
self.contacts = contacts; | |
}; | |
var map = function(contacts) { | |
var result = ko.observableArray(); | |
_.forEach(contacts, function(contact) { | |
var newPhoneNumbers = ko.observableArray(); | |
_.forEach(contact.numbers, function(number) { | |
newPhoneNumbers.push(new phoneModel(ko.observable(number.phoneNumber), ko.observable(number.phoneType))); | |
}); | |
result.push(new contactModel(ko.observable(contact.firstName), ko.observable(contact.lastName), newPhoneNumbers)); | |
}); | |
return result; | |
}; | |
var initialData = [ | |
{ firstName: "Michael", lastName: "Sarchet", numbers: [ | |
{ phoneNumber: "(361) 555-6338", phoneType: "Mobile" }, | |
{ phoneNumber: "(361) 555-6338", phoneType: "Other" }] | |
} | |
]; | |
var localViewModel = new viewModel(map(initialData)); | |
ko.applyBindings(localViewModel); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment