经过大量研究和反复试验,我还没有找到解决方案。请帮忙!代码中的 SearchCustomer 方法对有效和无效的场景进行了注释。
情况
我将knockoutjs与映射插件一起使用。我采用一个 View 模型,其中包含来自服务器的工作订单,它包含有关它的一些属性,以及它下面的客户模型和客户下面的联系人模型。
在工作订单屏幕上,用户可以搜索弹出模式搜索窗口的客户。他们选择该客户,并将客户的 ID 和客户模型返回到工作订单中。我更新工作订单的 customerID 没有问题,但是当我尝试更新客户数据(包括联系人)时,我收到了 Function Expected 错误。
代码
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;
})
}
谢谢大家!
最佳答案
由于 self.Workorder.Customer
最初是使用 ko.mapping
填充的,因此当您想要重新填充它时,应该使用 ko.mapping
> 再次,例如:
ko.mapping.fromJS(customer, self.Workorder.Customer)
关于javascript - Knockoutjs 函数更新模型时出现预期异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36227874/