I have a view which contains a template that has a foreach to loop round an array of models. However, the array of models comes from an ajax call.
Here is an example of the scenario:
// Contained Model
function SomeModel() {
var self = this;
this.Firstname = ko.observable();
this.Lastname = ko.observable();
this.Fullname = ko.dependentObservable(function() {
return this.Firstname + " " + this.Lastname;
}, self);
}
// View Model
function SomeViewModel() {
var self = this;
this.ArrayOfModels = ko.mapping.fromJS([]);
this.GetModelsByAjax = function() {
$.ajax(...);
};
this.SuccessfullyRetrievedModelsFromAjax = function(models) {
ko.mapping.updateFromJS(self.ArrayOfModels, models);
};
}
ko.applyBindings(new SomeViewModel());
Here's the View:
<HtmlGuff>
<div data-bind="template: {name: 'model-template', foreach: ArrayOfModels}"></div>
</HtmlGuff>
// Template
<HtmlGuff>
<h2 data-bind="text: Fullname">
<div data-bind="text: Firstname" />
<div data-bind="text: Lastname" />
</HtmlGuff>
And this is the json result from the ajax call:
[{
"Firstname": "Joe",
"Lastname": "Blogs"
}, {
"Firstname": "Foo",
"Lastname": "Bar"
}]
Currently I am just passing in []
to the model declaration, however I keep getting the following error:
Firstname is not defined
It breaks on this: return new Function("jQuery","$item", body);
.
Is there any way to do what I want to?