How do I initialize the viewModel first time the page is loaded?
The refresh from Ajax call works and loads the data correctly after the ajax call but on the first load the page does not know the model.
var viewModel = {};
$("#searchButton").click(function () {
var tc= $("#tc").val();
var y= $("#y").val();
$.ajax({
url: "Search/?t=" + tc+ "&y=" + y,
type:'GET',
dataType: 'json',
success: function (result) {
viewModel = new TourViewModel(result);
ko.applyBindings(viewModel);
}
});
});
function TourViewModel(data) {
var self = this;
var tourMapping = {};
self.selectedItem = ko.observable("");
self.lastSavedJson = ko.observable("");
self.saveMe = function () {
viewModel.selectedItem(this);
self.lastSavedJson(JSON.stringify(ko.toJS(self.selectedItem), null, 2));
$.ajax({
url: "SaveTour",
data: ko.toJSON({ tour:ko.toJS(self.selectedItem) }),
type: "post",
contentType: "application/json",
success: function (result)
{ alert(result) }
});
}
selectItem = function () {
self.selectedItem(this);
}
ko.mapping.fromJS(data, tourMapping, self);
};