使用 Knockout Js 的 Ajax 数据绑定 [英] Ajax data binding using Knockout Js

查看:25
本文介绍了使用 Knockout Js 的 Ajax 数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<头><script src="js/jquery1.9.js"></script><script src="js/knockout-3.3.0.js"></script><script src="js/knockout.mapping.js"></script><script src="model/usermodel.js"></script><身体><div><h1><span data-bind="text:user().name"></span></h1><h1><span data-bind="text:user().userName"></span></h1>

<script src="ViewModel/userDetailsViewModel.js"></script>

////型号////功能用户模型(结果){var self = this;this.name = ko.observable(result[0].name);///在ajax调用之前给我未定义的错误,在ajax调用之后我得到结果中的值this.userName = ko.observable();}/////查看模型////结果var userDetailsViewModel = 函数(结果){自我=这个;self.user = ko.observable(new userModel(result));};var mainUserDetailsViewModel = new userDetailsViewModel(result);ko.applyBindings(mainUserDetailsViewModel);////ajax在页面加载时调用////$.ajax({类型:POST",数据类型:json",url: baseUrl + 'api/xx/xxx',数据: jason.strigfy(),成功:功能(数据){结果=数据;////我得到的是结果json数据对象0=["name":"nnnn","Username":"mmmmmm"],////我将此结果传递给 ViewModel 和 Usermodel Constructor//mainUserDetailsViewModel.user(new userModel(result));},错误:函数(错误){jsonValue = jQuery.parseJSON(error.responseText);//jError('保存新部分源时出错:' + jsonValue, { TimeShown: 3000 });}});

解决方案

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

function UserViewModel() {var self = this;self.UsersList = ko.observableArray([]);self.GetUsers = function() {$.ajax({类型:POST",数据类型:json",url: baseUrl + 'api/xx/xxx',数据: jason.strigfy(),成功:功能(数据){//这里你映射并创建一个新的userDetailVM实例self.UsersList($.map(data, function (user) {返回新的 UserDetailViewModel(user);}));}});}//在加载VM时调用以获取用户列表,或者您可以在模型上的任何事件上调用它self.GetUsers();}函数 UserDetailViewModel(data){var self = this;self.Name = ko.observable(data.name);self.UserName = ko.observable(data.username);}ko.applyBindings(new UserViewModel());

查看:

 

<div data-bind="text: Name"></div><div data-bind="text: 用户名"></div>

i am using the knockout js, i am finding diffcult to bind the data while in ajax get method, i have created model, viewModel, and ajax function, i have the ajax method in the same js file where i have created viewModel i am calling the ajax on page load and trying to bind my html with konckout js, i am getting the error userModel is undefined if i give this.name = ko.observale(result[0].name) before the ajax call, after the ajax called it give name is undefined need help

<html>
  <head>
    <script src="js/jquery1.9.js"></script>
    <script src="js/knockout-3.3.0.js"></script>
    <script src="js/knockout.mapping.js"></script>
    <script src="model/usermodel.js"></script>
  </head>

  <body>

    <div>
      <h1><span data-bind="text:user().name"></span></h1>
      <h1><span data-bind="text:user().userName"></span></h1>
    </div>
    <script src="ViewModel/userDetailsViewModel.js"></script>
  </body>
</html>

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

解决方案

Here is my suggestion to have a clean nested view model.
Example : 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()); 

View :

 <h1 data-bind="foreach: UsersList">
    <div data-bind="text: Name"></div>
    <div data-bind="text: UserName"></div>
 </h1>

这篇关于使用 Knockout Js 的 Ajax 数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆