使用Knockout Js进行Ajax数据绑定

我正在使用淘汰赛js ,我发现diffcult绑定数据,而在ajax get方法,我已经创建了模型,viewModel和ajax函数,我有相同的js文件中的ajax方法,我创建了viewModel我正在调用页面上的ajax加载并尝试将我的html与konckout js绑定,我得到的错误userModel is undefined如果我在ajax调用之前给this.name = ko.observale(result[0].name) ,之后调用ajax它给name is undefined需要帮助

         

 ////Model//// function userModel(result) { var self = this; this.name = ko.observable(result[0].name); /// give me error undefined before the ajax call and after ajax call i get the value in result this.userName = ko.observable(); } /////View Model//// var result var userDetailsViewModel = function(result) { self = this; self.user = ko.observable(new userModel(result)); }; var mainUserDetailsViewModel = new userDetailsViewModel(result); ko.applyBindings(mainUserDetailsViewModel); ////ajax called on the page load //// $.ajax({ type: "POST", dataType: "json", url: baseUrl + 'api/xx/xxx', data: jason.strigfy(), success: function(data) { result = data; ////I am getting in result json data object 0=["name":"nnnn","Username":"mmmmmm"], //// i am passing this result to ViewModel and to Usermodel Constructor// mainUserDetailsViewModel.user(new userModel(result)); }, error: function(error) { jsonValue = jQuery.parseJSON(error.responseText); //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 }); } }); 

这是我建议有一个干净的嵌套视图模型。
示例: https : //jsfiddle.net/kyr6w2x3/28/

 function UserViewModel() { var self = this; self.UsersList = ko.observableArray([]); self.GetUsers = function() { $.ajax({ type: "POST", dataType: "json", url: baseUrl + 'api/xx/xxx', data: jason.strigfy(), success: function (data) { //Here you map and create a new instance of userDetailVM self.UsersList($.map(data, function (user) { return new UserDetailViewModel(user); })); } }); } //call to get users list when the VM is loading or you can call it on any event on your model self.GetUsers(); } function UserDetailViewModel(data){ var self = this; self.Name = ko.observable(data.name); self.UserName = ko.observable(data.username); } ko.applyBindings(new UserViewModel()); 

查看: