经过大量的研究和追踪和错误,我还没有找到解决方案。请帮忙!代码中的SearchCustomer方法对有效且不起作用的方案有评论。
场合
我使用knockoutjs和映射插件。我从服务器获取一个包含Workorder的视图模型,它包含一些关于它的属性以及它下面的Customer模型和Customer下面的Contact模型。
在工作订单屏幕上,用户可以搜索弹出模态搜索窗口的客户。他们选择该客户,并且客户的ID和客户模型返回到工作订单。我更新了工作订单的customerID没问题,但是当我尝试更新客户数据(包括联系人)时,我收到函数预期错误。
代码
function WorkorderViewModel(data) {
var self = this;
data = data || {};
mapping = {
'Workorder': {
create: function (options) {
return new Workorder(options.data, self);
}
}
}
ko.mapping.fromJS(data, mapping, self);
self.ViewCustomer = function () {
self.Workorder.Customer.View();
}
self.SearchCustomer = function () {
self.Workorder.Customer.Search(function (customerID, customer) {
self.Workorder.CustomerID(customerID); //Works
self.Workorder.Customer(customer) //Function Expected, I feel this should work! Please help!
self.Workorder.Customer = new Customer(customer, self.Workorder); //No Error doesn't update screen
self.Workorder.Customer.Contact.FirstName(customer.Contact.FirstName); //Works, updates screen, but I don't want to do this for every property.
self.Workorder.SaveAll(); //Works, reload page and customer data is correct. Not looking to reload webpage everytime though.
})
}
}
function Workorder(data, parent) {
var self = this;
data = data || {};
mapping = {
'Customer': {
create: function (options) {
return new Customer(options.data, self);
}
}
}
ko.mapping.fromJS(data, mapping, self);
}
function Customer(data, parent) {
var self = this;
data = data || {};
mapping = {
'Contact': {
create: function (options) {
return new Contact(options.data, self);
}
}
}
ko.mapping.fromJS(data, mapping, self);
}
function Contact(data, parent) {
var self = this;
data = data || {};
mapping = {};
ko.mapping.fromJS(data, mapping, self);
self.AddedOn = ko.observable(moment(data.AddedOn).year() == 1 ? '' : moment(data.AddedOn).format('MM/DD/YYYY'));
self.FullName = ko.computed(function () {
var fullName = '';
if (self.FirstName() != null && self.FirstName() != '') {
fullName = self.FirstName();
}
if (self.MiddleName() != null && self.MiddleName() != '') {
fullName += ' ' + self.MiddleName();
}
if (self.LastName() != null && self.LastName() != '') {
fullName += ' ' + self.LastName();
}
return fullName;
})
}
谢谢大家!
答案 0 :(得分:0)
尝试更改:
self.Workorder.Customer(customer);
为:
self.Workorder.Customer = customer;
我的猜测是,Workorder的Customer属性不是可观察的。
答案 1 :(得分:0)
由于self.Workorder.Customer
最初是使用ko.mapping
填充的,因此当您想要重新填充时,您应该再次使用ko.mapping
,例如:
ko.mapping.fromJS(customer, self.Workorder.Customer)