Initialize viewmodel and refresh after ajax seach results are back

77 views
Skip to first unread message

vs

unread,
Oct 20, 2017, 3:59:32 PM10/20/17
to KnockoutJS

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); };

Jean-Sebastien Binette

unread,
Nov 10, 2017, 5:12:25 PM11/10/17
to KnockoutJS
Your code is hard to read when posted like that but it seems you are specifying the view model on the ajax succes. That is a wrong way to do it. Create your view model. Add, say an empty ko observable array to it. The on the ajaxe success, set the array like viewmodel.myarray(result) and everything should work.
Reply all
Reply to author
Forward
0 new messages