Initialize viewmodel and refresh after ajax seach results are back

77 просмотров
Перейти к первому непрочитанному сообщению

vs

не прочитано,
20 окт. 2017 г., 15:59:3220.10.2017
– 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

не прочитано,
10 нояб. 2017 г., 17:12:2510.11.2017
– 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.
Ответить всем
Отправить сообщение автору
Переслать
0 новых сообщений