1

我有公司列表,点击每个公司时需要显示该公司的销售人员。

我为此尝试了淘汰赛。下面是脚本,您可以在http://jsfiddle.net/habdulha/gkqeD/29/中找到全部内容

列出了初始公司,但单击未加载销售人员的公司。

<!-- language: lang-js -->

var rootViewModel = function(companies) {
this.companiesModel = ko.observableArray(companies);
}

var companyModel = function(salesPersonModel) {
CompanyId = ko.observable();
Name = ko.observable();
SalesPersonList = ko.observableArray(salesPersonModel);
LoadSalesPerson = function() {

    var self = this;
    var postData = {
        companyId: this.CompanyId()
    }
    /// ajax to get the emp name based on company id
    var data = $.ajax({
        type: 'GET',
        url: '/echo/json/',
        data: postData,
        success: function(result) {
            /// result is based on companyid
            var ajaxReply = {
                "empName": "John",
                "empName": "John 1"
            };


            self.SalesPersonList = ko.observableArray(ko.mapping.fromJS(ajaxReply)());


        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
    }
  }

 var salesModel = function() {
  empName = ko.observable();
 }


  var myCompanyModelArray = new Array();
  var mySalesModelArray = new Array();
  mySalesModelArray[0] = new salesModel();
  myCompanyModelArray[0] = new companyModel(mySalesModelArray);
  var mainViewModel = new rootViewModel(myCompanyModelArray);
  ko.applyBindings(mainViewModel);

  $(document).ready(function() {
      var data = $.ajax({
      type: 'GET',
      url: '/echo/json/',
      //// get all the companies
      success: function(data) {
        var ajaxReply = {
            {
                "CompanyId ": "1",
                "Name ": "Comp 1"
            }, {
                "CompanyId ": "2",
                "Name ": "Comp 2"
            }
        };
        residencyViewModel.yearGroupModel(ko.mapping.fromJS(ajaxReply)());

    },
    error: function(xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
    }
   });

  });
4

2 回答 2

1

问题出在这行代码中:

self.SalesPersonList = ko.observableArray(ko.mapping.fromJS(ajaxReply)());

SalesPersonList是一个可观察的数组,所以当它绑定到你的 UI 时,Konckout 会观察数组的变化。在上面的代码中,您只是用一个新实例替换您的数组。要完成这项工作,您需要替换绑定到 UI 的数组的内容,而不是替换数组本身...

self.SalesPersonList.RemoveAll();
for(var item in ko.mapping.fromJS(ajaxReply)()) {
  self.SalesPersonList.push(item);
}
于 2012-01-14T08:01:24.080 回答
1

我有同样的问题,但@ColinE 的答案对我不起作用,但这个想法是正确的......

在我的情况下,我以 JSON 格式接收项目列表,并在映射后将它们添加到可观察数组中。

$.getJSON("/Path/To/Json/Service", function (r) {

    self.SalesPersonList.removeAll();

    // loop through each item returned
    $.each(r, function (i, v) {
        // add a mapped item to the array
        self.SalesPersonList.push(ko.mapping.fromJS(v)); 
    });

});
于 2012-01-17T12:26:47.557 回答