KnockoutJS - observableArray and ko.mapping.fromJS
http://stackoverflow.com/questions/6637579/knockoutjs-observablearray-and-ko-mapping-fromjs
by rniemeyer
HTML
<script src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script src="http://knockoutjs.com/downloads/knockout-1.2.1.debug.js"></script>
<script src="https://rawgithub.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.debug.js"></script>
<button data-bind="click: GetModelsByAjax">Go</button>
<div data-bind="template: {name: 'model-template', foreach: ArrayOfModels}"></div>
<script id="model-template" type="text/html">
<div data-bind="text: Firstname"></div>
<div data-bind="text: Lastname"></div>
</script>
JavaScript
// Contained Model
function SomeModel() {
this.Firstname = ko.observable();
this.Lastname = ko.observable();
}
// View Model
function SomeViewModel() {
var self = this;
this.ArrayOfModels = ko.mapping.fromJS([]);
this.GetModelsByAjax = function() {
$.ajax({
type: 'POST',
url: '/echo/json/',
data: {
json: JSON.stringify([{
Firstname: "Bob",
Lastname: "Smith"},
{
Firstname: "Ted",
Lastname: "Smith"}]),
delay: 0
},
context: this,
success: function(data) {
self.SuccessfullyRetrievedModelsFromAjax(data);
},
dataType: 'json'
});
};
this.SuccessfullyRetrievedModelsFromAjax = function(models) {
ko.mapping.fromJS(models, self.ArrayOfModels);
};
}
ko.applyBindings(new SomeViewModel());