我有公司列表,点击每个公司需要显示该公司的销售人员。
我为此尝试了淘汰赛。下面是脚本以及您可以在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);
}
});
});
答案 0 :(得分: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);
}
答案 1 :(得分:1)
我遇到了同样的问题,但是@ColinE的答案对我不起作用,但这个想法是正确的......
在我的情况下,我收到JSON项目列表,并在映射后将它们添加到observable数组。
$.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));
});
});