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.
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.
Then your ajax results would have something like this :
This might not be exactly right, but should get you close…