Reputation: 11177
I have a knockoutjs viewmodel defined like this:
function TestViewModel() {
var self = this;
self.matches = ko.observableArray([]);
self.selectedItem = ko.observable(self.matches()[0]);
self.SelectMatch = function (match) {
self.selectedItem(match);
};
self.setMatchList = function (_data) {
self.matches(_data);
};
}
I also have a function that gets called from a click event using straight javascript -- no knockoutjs databinding involved. The script retreives a JSON array from the server like so:
$.ajax({
type: 'post',
contentType: "application/json; charset=utf-8",
url: "/FindMatches",
timeout: 10000,
data: JSON.stringify({ firstname: $("#Person_ProperFirstname").val(), lastname: $("#Person_ProperLastname").val(), gender: $("#Person_Gender").val().substring(0, 1) }),
success: function (results) {
if (results.length < 1) {
//setErrorMessage("No matches were found.");
}
else {
//setErrorMessage("");
$.each(results, function (item) {
TestViewModel.matches.push(item);
});
$("#parent_dialog").dialog("open");
}
Now I want to update the matches observableArray on my viewmodel with the results returned from the server but I'm having trouble figuring out how to do this. Besides what you see in the above script, I've also tried the following:
else {
TestViewModel.matches(results);
}
//also this
else {
TestViewModel.setMatchList(results); }
Any help would be greatly appreciated.
Upvotes: 2
Views: 1914
Reputation: 17282
I think the data is an object and you need it to be an array. I've used the mapping plugin to do the conversion easily for me:
$.getJSON('/casestudies', function(data) {
vm.casestudies = ko.mapping.fromJS(data);
ko.applyBindings(vm);
});
Else, for your example, you'll have to do the mapping manually:
$.each(results, function (item) {
TestViewModel.matches.push(item);
});
The item above is still an object, so you also need to foreach the item's properties and map it to your ko's model, have a look at ko's json page:
// Load and parse the JSON
var someJSON = /* Omitted: fetch it from the server however you want */;
var parsed = JSON.parse(someJSON);
// Update view model properties
viewModel.firstName(parsed.firstName);
viewModel.pets(parsed.pets);
Upvotes: 0
Reputation: 11096
I'm assuming that your code initializes your ko bindings with a line similar to :
ko.applyBindings(new TestViewModel(data.d));
If you will create a variable of the instance of your model, you could reference it in other code.
var _tvm = new TestViewModel(data.d);
ko.applyBindings(_tvm);
Then your ajax results would have something like this :
else {
_tvm.matches(results);
}
This might not be exactly right, but should get you close...
Upvotes: 3